Java 2个线程按顺序打印数字
我有线程t1打印Java 2个线程按顺序打印数字,java,multithreading,Java,Multithreading,我有线程t1打印奇数1 3 5 7… 我有线程t2打印偶数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 c
奇数1 3 5 7…
我有线程t2打印偶数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);
您需要线程之间进行某种通信,以协调它们以交替顺序打印值。