我有螺纹T1打印odd number 1 3 5 7...
2个线程在顺序打印数
我有螺纹T2打印even number 0 2 4 6 ...
我想按顺序将被打印的输出从该两个线程等
0 1 2 3 4 5 6 7
我不想在这里的代码,请指导我在Java中使用什么框架?
我有螺纹T1打印odd number 1 3 5 7...
2个线程在顺序打印数
我有螺纹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);
您需要某些线程之间的通信来协调它们以交替顺序打印值。 – MrSmith42 2013-02-23 20:07:27
我想了解尝试一些例子的多线程概念。 – chiru 2013-02-23 20:09:48