[英]2 threads printing numbers in sequence
我有线程t1打印odd number 1 3 5 7...
我有线程t2打印even number 0 2 4 6 ...
我希望输出从这两个线程按顺序打印
0 1 2 3 4 5 6 7
我不想在这里的代码请指导我在java中使用什么框架?
让两个线程交替的最简单方法是每个线程创建一个java.util.concurrent.CountDownLatch
,在打印后设置为1,然后等待另一个线程释放其锁存器。
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
我可能做的事情如下:
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;
}
}
线程1:
while (true)
{
if (!Counter.incrementAndPrint(true))
Thread.sleep(1); // so this thread doesn't lock up processor while waiting
}
线程2:
while (true)
{
if (!Counter.incrementAndPrint(false))
Thread.sleep(1); // so this thread doesn't lock up processor while waiting
}
可能不是最有效的做事方式。
两个信号量,每个线程一个。 使用信号量在线程之间发出'printToken'信号。 伪:
CreateThread(EvenThread);
CreateThread(OddThread);
Signal(EvenThread);
..
..
EvenThread();
Wait(EvenSema);
Print(EvenNumber);
Signal(OddSema);
..
..
OddThread();
Wait(OddSema);
Print(OddNumber);
Signal(EvenSema);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.