Issue
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 6
T1 7
T2 8
T3 9
...and so on.
Here is the
public class ThreadNumberPrinter {
Object monitor = new Object();
AtomicInteger number = new AtomicInteger(1);
public static void main(String[] args) {
ThreadNumberPrinter tnp = new ThreadNumberPrinter();
Thread t1 = new Thread(tnp.new Printer(1, 3));
Thread t2 = new Thread(tnp.new Printer(2, 3));
Thread t3 = new Thread(tnp.new Printer(3, 3));
t3.start();
t1.start();
t2.start();
}
class Printer implements Runnable {
int threadId;
int numOfThreads;
public Printer(int id, int nubOfThreads) {
threadId = id;
this.numOfThreads = nubOfThreads;
}
public void run() {
print();
}
private void print() {
try {
while (true) {
Thread.sleep(1000l);
synchronized (monitor) {
if (number.get() % numOfThreads != threadId) {
monitor.wait();
} else {
System.out.println("ThreadId [" + threadId
+ "] printing -->"
+ number.getAndIncrement());
monitor.notifyAll();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
But just after 2nd thread runs and prints the number 2, all thread get into wait stage and nothing gets printed. I am not sure where I am doing wrong. Any help would be greatly appreciated.
Solution
Well, the problem is that modulo 3 % 3
is 0
. Change your threadId
s to 0..2
instead of 1..3
and hopefully it should work.
Answered By - sodik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.