Reputation: 832
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?
Upvotes: 3
Views: 2993
Reputation: 24847
Two semaphores, one for each thread. Use the semaphores to signal a 'printToken' between the threads. Pseudo:
CreateThread(EvenThread);
CreateThread(OddThread);
Signal(EvenThread);
..
..
EvenThread();
Wait(EvenSema);
Print(EvenNumber);
Signal(OddSema);
..
..
OddThread();
Wait(OddSema);
Print(OddNumber);
Signal(EvenSema);
Upvotes: 1
Reputation: 55609
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.
Upvotes: 1
Reputation: 47964
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
Upvotes: 4