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
I have tried it below simple way to print in sequence using three threads and it is working well.
public class AppPrint123 {
static int count = 1;
static int counter = 1;
static Object lock = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
while (true) {
synchronized (lock) {
try {
Thread.sleep(100);
while (count != 1) {
lock.wait();
}
System.out.println(Thread.currentThread().getName() + ": " + counter);
count++;
counter++;
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notifyAll();
}
}
}
}, "T1");
Thread t2 = new Thread(new Runnable() {
public void run() {
while (true) {
synchronized (lock) {
try {
Thread.sleep(100);
while (count != 2) {
lock.wait();
}
System.out.println(Thread.currentThread().getName() + ": " + counter);
counter++;
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notifyAll();
}
}
}
}, "T2");
Thread t3 = new Thread(new Runnable() {
public void run() {
while (true) {
synchronized (lock) {
try {
Thread.sleep(100);
while (count != 3) {
lock.wait();
}
System.out.println(Thread.currentThread().getName() + ": " + counter);
count = count - 2;
counter++;
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notifyAll();
}
}
}
}, "T3");
t1.start();
t2.start();
t3.start();
}
}
You can print count variable instead if you want to generate output like 123123123 in sequence using three threads.
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.