Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 threads printing numbers in sequence

I have thread t1 printing odd number 1 3 5 7...

I have thread t2 printing even number 0 2 4 6 ...

I want the output to be printed in sequential order from this two threads like

 0 1 2 3 4 5 6 7

I do not want code here please guide me with what framework to use in java?

like image 324
chiru Avatar asked Sep 02 '26 00:09

chiru


2 Answers

The easiest way to have two threads alternate is for each one to create a java.util.concurrent.CountDownLatch set to a count of 1 after it prints, and then wait for the other thread to release its latch.

Thread A: print 0
Thread A: create a latch
Thread A: call countDown on B's latch
Thread A: await
Thread B: print 1
Thread B: create a latch
Thread B: call countDown on A's latch
Thread B: await
like image 175
Affe Avatar answered Sep 03 '26 15:09

Affe


I'd probably do something like:

public class Counter
{
  private static int c = 0;

  // synchronized means the two threads can't be in here at the same time
  // returns bool because that's a good thing to do, even if currently unused
  public static synchronized boolean incrementAndPrint(boolean even)
  {
    if ((even  && c % 2 == 1) ||
        (!even && c % 2 == 0))
    {
      return false;
    }
    System.out.println(c++);
    return true;
  }
}

Thread 1:

while (true)
{
  if (!Counter.incrementAndPrint(true))
    Thread.sleep(1); // so this thread doesn't lock up processor while waiting
}

Thread 2:

while (true)
{
  if (!Counter.incrementAndPrint(false))
    Thread.sleep(1); // so this thread doesn't lock up processor while waiting
}

Possibly not the most efficient way of doing things.

like image 38
Bernhard Barker Avatar answered Sep 03 '26 15:09

Bernhard Barker