Thread 1 prints A1 A2 A3. Thread 2 prints B1 B2 B3. I want to write a program that will make sure when both threads run the output will be A1 B1 A2 B2 A3 B3. So far I have come up with below program. Please let me know how this can be simplified? Can we use less Semaphores? Can this be achieved using wait() notify()?
package com.MultiThreading.threadSerialization;
import java.util.concurrent.Semaphore;
public class ThreadSerialization {
Semaphore a1Done = new Semaphore(0);
Semaphore b1Done = new Semaphore(0);
Semaphore a2Done = new Semaphore(0);
Semaphore b2Done = new Semaphore(0);
Semaphore a3Done = new Semaphore(0);
/**
* methodA prints : A1 A2 A3
*/
public void methodA() {
System.out.println("A1");
a1Done.release();
b1Done.acquire();
System.out.println("A2");
a2Done.release();
b2Done.acquire();
System.out.println("A3");
a3Done.release();
}
/**
* methodB prints : B1 B2 B3
*/
public void methodB() {
a1Done.acquire();
System.out.println("B1");
b1Done.release();
a2Done.acquire();
System.out.println("B2");
b2Done.release();
a3Done.acquire();
System.out.println("B3");
}
public void createTwoThreads() throws InterruptedException{
ThreadSerialization ts = new ThreadSerialization();
Thread T1 = new Thread(() -> ts.methodA());
Thread T2 = new Thread(() -> ts.methodB());
T1.start();
T2.start();
Thread.sleep(5000);
System.out.println("test done");
}
}