Java Thread - i want to generate numbers in sequence eg: 1,2,3,4... (there will be 2 threads only ) 1st thread o/p will be 1 ,second thread o/p will be 2 , again 1st thread o/p will be 3 and so on , it can be upto 10 or upto n number whatever just wanna get the logic please help me guys :|
below is my attempt to do it but its not working i know there would be wait() and notify() methods for sure but cant figure out the proper way to use them !
class NumberGenerator { static int number = 0;
synchronized public int numGenerator()
{
for(int i=0;i<20;i++)
{
System.out.println(i);
number=i;
}
return number;
}
}
class FirstThreadClass extends Thread { NumberGenerator num;
FirstThreadClass(NumberGenerator num)
{
this.num = num;
}
public void run()
{
System.out.println("i am from 1st thread :"+num.numGenerator());
}
}
class SecondThreadClass extends Thread { NumberGenerator num;
SecondThreadClass(NumberGenerator num)
{
this.num = num;
}
public void run()
{
System.out.println("i am from 2nd thread :"+num.numGenerator());
}
}
public class ThreadTesting { public static void main(String[] args) {
FirstThreadClass ftc = new FirstThreadClass(new NumberGenerator());
SecondThreadClass stc = new SecondThreadClass(new NumberGenerator());
ftc.start();
stc.start();
}
}
you can achieve this using cyclic barrier, create a barrier and once two threads have generated one number each print the two numbers