2013-03-25 81 views
0

雖然在網上遇到一些問題,但我發現了這一點。不知道如何解決這個問題。如何讓兩個線程彼此等待執行任務?

我想線程1先運行和計算foo和等待,然後希望線程2運行和計算foo和終於想線程1繼續並打印foo和完整的執行。

我想它,因爲最後1小時,沒有能夠解決。任何幫助表示讚賞。謝謝。

public class ThreadTest { 

    private static class Thread01 extends Thread { 

     private Thread02 _thread02; 
     public int foo = 0; 

     public void setThread02(Thread02 thread02) { 
      _thread02 = thread02; 
     } 

     public void run() { 

      try { 
       for (int i = 0; i < 10; i++) foo += i; 
       synchronized (this) { this.notify(); } 
       synchronized (_thread02) { _thread02.wait(); } 
       System.out.println("Foo: " + _thread02.foo); 
      } catch (InterruptedException ie) { ie.printStackTrace(); } 
     } 
    } 


private static class Thread02 extends Thread { 

     private final Thread01 _thread01; public int foo = 0; 

     public Thread02(Thread01 thread01) { 
      _thread01 = thread01; 
     } 

     public void run() { 

      try { 
       synchronized (_thread01) { _thread01.wait(); } 
       foo = _thread01.foo; 
       for (int i = 0; i < 10; i++) foo += i; 
       synchronized (this) { this.notify(); } 
      } catch (InterruptedException ie) { ie.printStackTrace(); } 
     } 
    } 

    public static void main(String[] args) throws Exception { 

     Thread01 thread01 = new Thread01(); 
     Thread02 thread02 = new Thread02(thread01); 
     thread01.setThread02(thread02); 

     thread01.start(); 
     thread02.start(); 
     thread01.join(); 
     thread02.join(); 
    } 
} 
+3

我不知道爲什麼,但字段名稱前使用下劃線讓我想殺人的東西! – 2013-03-25 00:25:27

回答

3

而不必在你的代碼看起來多少,我覺得它的工作原理是這樣的:

線程1計算FOO,創建並啓動線程2.線程1調用thread2.join()。這樣線程1將被掛起,直到線程2完成。然後,只需繼續線程1

需要任何通知的最終代碼,只是一個簡單的join()

+0

你至少可以看看這個問題=) – ddmps 2013-03-25 00:23:51

+0

@Pescis沒有。我的回答完全是他想達到的。 – Sebastian 2013-03-25 00:25:04

+0

我認爲這是一個在SSSCE上失敗的嘗試,並且他確實想要在thread2完成計算foo時執行某些操作(否則整個線程完全無用,並且可以使用一個線程完成)。 – ddmps 2013-03-25 00:36:14

2

一種可以替代的通知/等待這樣的代碼是使用BlockingQueueLinkedBlockingQueue。隨着2 BlockingQueue秒,兩個線程可以互相等待,並通過郵件來回,沒有你寫的所有的等待和通知代碼可能是複雜的,充滿了錯誤。

相關問題