Program to print in sequence with Threads in java Thread1 = 1 Thread2 = 2 Thread3 = 3 Thread1 = 4 Thread2 = 5 Thread3 = 6



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() {
          lbqnew 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);
                       ilbq.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 m1new MyRunnable();
          MyRunnable m2new MyRunnable();
          MyRunnable m3new MyRunnable();

          m1.nextm2//Chain all the objects
          m2.nextm3;
          m3.nextm1;

          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 >

Implement Thread pool in java

Implementing ThreadPool using custom LinkedBlockingQueue

ThreadLocal in multithreading in java - methods and usage with program

Busy Spin - What is busy spin? Consumer Producer problem with busy spin and solution to busy spin.

ThreadGroup in java

Demonstrate ThreadGroup's important methods in DETAIL


eEdit
Must read for you :