Print 1,2,3 using three threads Java

Before jumping into this problem, I recommend to go through printing odd, even numbers using 2 threads post. In this problem, We used a single Boolean object which has three valuesβ€Šβ€”β€Štrue, false, null.

When true we will print 1 while other 2 threads will be waiting for their turn. When first thread is done with printing, it will call notifyAll() on the object and gives the access to second thread with the help of isTurn variable.

Then, the second thread will print 2 while other threads are waiting. Then, second thread will call notifyAll(). The variable isTurn is deciding which thread should get access to the object. Now, the access will be passed to third thread and other threads will be waiting.

The same logic of passing the control from first thread to second thread, from second thread to third thread and from third thread to first thread again continues till the loop ends.

The final Output will be like below. 

Java 1,2,3 multithreading output



Code


public class file {
static final String one = " ONE_THREAD";
static final String two = " TWO_THREAD";
static final String three = " THREE_THREAD";
public static void main(String[] args) {
SharedPrinter sharedPrinter = new SharedPrinter();
Thread oneThread = new Thread(new Task(sharedPrinter, true), one);
Thread twoThread = new Thread(new Task(sharedPrinter, false), two);
Thread threeThread = new Thread(new Task(sharedPrinter, null), three);
oneThread.start();
twoThread.start();
threeThread.start();
}
}
view raw ThreeThreads.java hosted with ❀ by GitHub
class Task implements Runnable {
private SharedPrinter sharedPrinter;
private Boolean isTurn;
public Task(SharedPrinter sharedPrinter, Boolean isEven) {
this.sharedPrinter = sharedPrinter;
this.isTurn = isEven;
}
@Override
public void run() {
int number = isTurn != null ? (isTurn ? 1 : 2) : 3;
while (number <= 10) {
sharedPrinter.printNumber(number, isTurn);
number += 3;
}
}
}
view raw ThreeThreadsTask.java hosted with ❀ by GitHub
class SharedPrinter {
private volatile Boolean isTurn = true;
synchronized void printNumber(int number, Boolean isTurn) {
try {
while (this.isTurn != isTurn) {
wait();
}
System.out.println(number + Thread.currentThread().getName());
if (this.isTurn != null && this.isTurn) {
this.isTurn = false;
} else if (this.isTurn != null && !this.isTurn) {
this.isTurn = null;
} else {
this.isTurn = true;
}
Thread.sleep(1000);
notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
view raw SharedPrinter.java hosted with ❀ by GitHub

1 Comments

Post a Comment