Print in sequence with Threads in java
Example >
Thread1 = 1
Thread2 = 2
Thread3 = 3
Thread1 = 4
Thread2 = 5
Thread3 = 6
Thread1 = 7
Thread2 = 8
Thread3 = 9
Program to print in sequence with Threads in java Thread1 = 1 Thread2 = 2 Thread3 = 3 Thread1 = 4 Thread2 = 5 Thread3 = 6
We will use LinkedBlockingQueue to solve this problem.
import java.util.concurrent.LinkedBlockingQueue;
class MyRunnable implements Runnable {
MyRunnable next;
LinkedBlockingQueue<Integer> lbq;
MyRunnable() {
lbq = new LinkedBlockingQueue<>();
}
void accept(int i) {
try {
lbq.put(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() {
int i = 0;
while (true) {
try {
Thread.sleep(1000);
i = lbq.take(); //It will wait till lbq.put(i); is called ,
//so only one thread will call it a time
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " = " + i);
next.accept(++i); //Now, current thread is executed , calling accept will call ,
//lbq.put(i), which will end blocking state of thread on onext object
}
}
}
public class ThreadsSequence_blockingQueue_Blog {
public static void main(String[] args) {
MyRunnable m1 = new MyRunnable();
MyRunnable m2 = new MyRunnable();
MyRunnable m3 = new MyRunnable();
m1.next = m2; //Chain all the objects
m2.next = m3;
m3.next = m1;
new Thread(m1, "Thread1").start();
new Thread(m2, "Thread2").start();
new Thread(m3, "Thread3").start();
m1.accept(1); //Wait make first thread to run
}
}
/*output
Thread1 = 1
Thread2 = 2
Thread3 = 3
Thread1 = 4
Thread2 = 5
Thread3 = 6
Thread1 = 7
Thread2 = 8
Thread3 = 9
*/
|
RELATED LINKS>
Thread Pool, Thread local, Busy Spin, ThreadGroup >