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 ThreadTask implements Runnable {
private int counter;
private int threadID;
private final Object lock;
private int prev;
public ThreadTask(Object obj, int threadid, int counter){
this.lock = obj; // monitor
this.threadID = threadid; //id of thread
this.counter = counter;
this.prev =threadid + 1;
}
public void run(){
while(counter<100){
synchronized(lock){
if(counter == this.prev && this.threadID % 3 == this.threadID){
System.out.println("T" + this.threadID + " = " + this.prev);
this.prev = this.prev + 3;
}
counter++;
lock.notifyAll();
try{
lock.wait();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
public class ThreadMain {
static volatile int counter = 1;
public static void main(String args[]) throws InterruptedException{
final Object lock = new Object();
ThreadTask first = new ThreadTask(lock, 0, counter);
ThreadTask second = new ThreadTask(lock, 1, counter);
ThreadTask third = new ThreadTask(lock, 2, counter);
Thread t1 = new Thread(first, "first");
Thread t2 = new Thread(second, "second");
Thread t3 = new Thread(third, "third");
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
}