2013-03-25 82 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秒,两个线程可以互相等待,并通过邮件来回,没有你写的所有的等待和通知代码可能是复杂的,充满了错误。

相关问题