samedi 11 avril 2015

How to print non repeating element by two threads?

i want to print non repeating elements from the same resource by two threads.


here in below code , am printing repeated elements



class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}

public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
}


The output :


1 1 2 2 3 3 4 4 . I want, if one thread prints "1" other thread should not print "1" again instead it should print 2 . How to achieve this condition? Thanks.


Aucun commentaire:

Enregistrer un commentaire