2014-11-23 148 views
0

我有两个线程类:一个打印数字从0到9,另一个从100到109.我想要的是让第一个线程等待另一个完成。为此,我使用了join()方法,但它不起作用。请告诉我哪里出错:使一个线程等待另一个完成

//demonstrates the use of join() to wait for another thread to finish 
class AThread implements Runnable { 
    Thread t; 

    AThread() { 
     t = new Thread(this); 
    } 

    public void run() { 
     try { 
      for (int i=0; i<10; i++) { 
       System.out.println(i); 
       Thread.sleep(10); 
      } 
     } catch (InterruptedException e) { 
      System.out.println(t + " interruped."); 
     } 
    } 

    public void halt(Thread th) { 
     try { 
      th.join(); 
     } catch (InterruptedException e) { 
      System.out.println(t + " interruped."); 
     } 
    } 
} 

//a different thread class (we distinguish threads by their output) 
class BThread implements Runnable { 
    Thread t; 

    BThread() { 
     t = new Thread(this); 
    } 

    public void run() { 
     try { 
      for (int i=100; i<110; i++) { 
       System.out.println(i); 
       Thread.sleep(10); 
      } 
     } catch (InterruptedException e) { 
      System.out.println(t + " interruped."); 
     } 
    } 
} 

public class WaitForThread { 
    public static void main(String[] args) { 
     AThread t1 = new AThread(); 
     BThread t2 = new BThread(); 

     t1.t.start(); 
     t1.halt(t2.t); //wait for the 100-109 thread to finish 
     t2.t.start(); 
    } 
} 
+0

为什么不使用wait()和notify方法实现它?它对于内部线程通信更有意义。 – BatScream 2014-11-23 07:27:05

+0

@BatScream我只是在学习绳索,实际上。 :-) – dotslash 2014-11-23 07:34:15

回答

2

您在线程开始之前调用join。这是行不通的;在这种情况下,join将立即返回,它不会等待另一个线程启动并稍后停止。您可以在API文档中看到这一点:

Thread.join()

此实现使用的this.wait电话空调上this.isAlive循环。

Thread.isAlive()

测试线程是否还活着。线程还活着如果它已经启动并且还没有死亡。

重新排序报表在main方法

t1.t.start(); 
t2.t.start(); 
t1.halt(t2.t); //wait for the 100-109 thread to finish 

编辑回答您的问题在意见:

如果你想在AThread线程等待在BThread线程在完成工作之前完成,那么您需要拨打AThread.run中的join,并更改main方法:

class AThread implements Runnable { 
    Thread t; 
    Thread threadToWaitFor; 

    AThread(Thread threadToWaitFor) { 
     t = new Thread(this); 
     this.threadToWaitFor = threadToWaitFor; 
    } 

    public void run() { 
     // First wait for the other thread to finish 
     threadToWaitFor.join(); 

     // ... 
    } 

    // ... 
} 

public class WaitForThread { 
    public static void main(String[] args) { 
     BThread t2 = new BThread(); 
     AThread t1 = new AThread(t2.t); 

     t2.t.start(); 
     t1.t.start(); 
    } 
} 
+0

我重新排列了语句,但两个线程仍然并行运行。睡眠()方法会导致问题吗? – dotslash 2014-11-23 07:34:42

+0

不,这是因为你的代码的结构。请注意,您实际上使** main **线程等待而不是't1'线程,因为您正在从主线程调用'join()'。你的代码没有做任何事情来阻止线程并行运行。 – Jesper 2014-11-23 07:37:35

+0

嗯......我以为在t1上打过电话,并且通过t2就足够了。那我应该怎么做呢?或者整个'join()'方法不适合? – dotslash 2014-11-23 07:43:11

相关问题