2013-02-23 69 views
3

我有螺紋T1打印odd number 1 3 5 7...2個線程在順序打印數

我有螺紋T2打印even number 0 2 4 6 ...

我想按順序將被打印的輸出從該兩個線程等

0 1 2 3 4 5 6 7 

我不想在這裏的代碼,請指導我在Java中使用什麼框架?

+4

您需要某些線程之間的通信來協調它們以交替順序打印值。 – MrSmith42 2013-02-23 20:07:27

+0

我想了解嘗試一些例子的多線程概念。 – chiru 2013-02-23 20:09:48

回答

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

我可能會做這樣的事情:

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 
} 

也許不能做的最有效的方法的東西。

1

兩個信號量,每個線程一個。使用信號量來表示線程之間的'printToken'。僞代碼:

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