I am trying to write a simple code to print numbers in sequence. Scenario is like
Thread Number
T1 1
T2 2
T3 3
T1 4
T2 5
T3
public class EvenOdd1 {
//public static String str ="str1";
public static void main(String[] args) {
// TODO Auto-generated method stub
EvenOdd1 edd1 = new EvenOdd1();
AbThread tr2 = new AbThread(0,edd1);
AbThread tr3 = new AbThread(1,edd1);
AbThread tr4 = new AbThread(2,edd1);
tr2.start();
tr3.start();
tr4.start();
}
}
class AbThread extends Thread {
int mod;
int mod_count=1;
EvenOdd1 edd1;
public static int count=1;
int num_thread=3;
public AbThread(int mod,EvenOdd1 edd1){
this.mod = mod;
this.edd1 = edd1;
}
public void run()
{
synchronized(edd1)
{
try{
while(true){
while(count%num_thread!=mod)
edd1.wait();
if(count==30)
break;
print();
edd1.wait();
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void print()
{
int val = mod==1?2*mod_count:(mod==2?3*mod_count:4*mod_count);
System.out.println(Thread.currentThread().getName() + " : " + val);
edd1.notifyAll();
count=count+1;
this.mod_count++ ;
}
}