Print sequence using three threads in java

In this post, we will see how to print sequence using three threads in java.

Problem

We need to print sequence 3 threads as below.
Example

Thread 1 –> 1
Thread 2 –> 2
Thread 3 –> 3
Thread 1 –> 4
Thread 2 –> 5
Thread 3 –> 6
Thread 1 –> 7
Thread 2 –> 8
Thread 3 –> 9
Thread 1 –> 10

Here is simple program which can print about sequence.

Create main program as below to execute.

Output

Thread 1 –> 1
Thread 2 –> 2
Thread 3 –> 3
Thread 1 –> 4
Thread 2 –> 5
Thread 3 –> 6
Thread 1 –> 7
Thread 2 –> 8
Thread 3 –> 9
Thread 1 –> 10
Thread 2 –> 11
Thread 3 –> 12
Thread 1 –> 13
Thread 2 –> 14
Thread 3 –> 15
Thread 1 –> 16
Thread 2 –> 17
Thread 3 –> 18
Thread 1 –> 19
Thread 2 –> 20
Thread 3 –> 21
Thread 1 –> 22
Thread 2 –> 23
Thread 3 –> 24
Thread 1 –> 25

Explanation

  • If num%3!=1, then thread 1 will go into wait state, otherwise it will print the number.
  • If num%3!=2, then thread 1 will go into wait state, otherwise it will print the number.
  • If num%3!=0, then thread 2 will go into wait state, otherwise it will print the number.
  • Please note that we have taken class level lock here, because we are using two different runnable object to print the sequence.

Leave a Reply

Your email address will not be published. Required fields are marked *