2个线程按顺序打印数字

时间:2013-02-23 20:03:55

标签: java multithreading

我有线程t1打印odd number 1 3 5 7...

我有线程t2打印even number 0 2 4 6 ...

我希望从这两个线程(如

)按顺序打印输出
 0 1 2 3 4 5 6 7

我不想在这里使用代码请指导我在java中使用什么框架?

3 个答案:

答案 0 :(得分:4)

让两个线程交替的最简单方法是,每个线程在打印后创建一个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

答案 1 :(得分:1)

我可能会做类似的事情:

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
}

可能不是最有效的做事方式。

答案 2 :(得分:1)

两个信号量,每个线程一个。使用信号量在线程之间发出'printToken'信号。伪:

CreateThread(EvenThread);
CreateThread(OddThread);
Signal(EvenThread);
..
..
EvenThread();
  Wait(EvenSema);
  Print(EvenNumber);
  Signal(OddSema);
..
..
OddThread();
  Wait(OddSema);
  Print(OddNumber);
  Signal(EvenSema);