函数Join()在java线程中

时间:2014-04-04 01:39:03

标签: java multithreading

我有这段代码:

class PrintDemo {  
  public void printCount(){
    try {
      for(int i = 5; i > 0; i--) {
        System.out.println("Counter   ---   "  + i );
      }
    } catch (Exception e) {
      System.out.println("Thread  interrupted.");
    }
  }
}

class ThreadDemo extends Thread {
  private Thread t;
  private String threadName;
  PrintDemo  PD;

  ThreadDemo( String name, PrintDemo pd) {
    threadName = name;
    PD = pd;
  }

  public void run() {
    synchronized(PD) {
      PD.printCount();
    }
    System.out.println("Thread " +  threadName + " exiting.");
  }

  public void start () {
    System.out.println("Starting " +  threadName);
    if (t == null) {
      t = new Thread (this, threadName);
      t.start ();
    }
  }
}

public class TestThread {
  public static void main(String args[]) {

    PrintDemo PD = new PrintDemo();

    ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );
    ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

    T1.start();
    T2.start();

    // wait for threads to end
    try {
      T1.join();
      T2.join();
    } catch( Exception e) {
      System.out.println("Interrupted");
    }
    System.out.println("hello");
  }
}

当我运行此时,hello消息最后没有显示。它假设主线程会等待其他人正确结束????

提前致谢。

2 个答案:

答案 0 :(得分:2)

ThreadDemo类,这是非常错误的。我很遗憾地称之为,但这不是一件好事。

特别指出一些事情:

public void start () {
  System.out.println("Starting " +  threadName);
  if (t == null) {
    t = new Thread (this, threadName);
    t.start ();
  }
}

这会在稍后调用join的ThreadDemo实例中启动新的,不同的主题未删除从不这样做。 join永远不会返回,因为ThreadDemo线程永远不会启动。

相反,您的PrintDemo可以实现Runnable,然后您可以将其传递给Thread。

class PrintDemo implements Runnable {
    @Override
    public synchronized void run() {
        for(int i = 5; i > 0; i--) {
            System.out.println("Counter   ---   "  + i );
        }
    }
}

class Main {
    public static void main(String[] args) {
        PrintDemo pd = new PrintDemo();

        Thread t1 = new Thread(pd);
        Thread t2 = new Thread(pd);

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch(InterruptedException ie) {
            System.err.println(ie);
        }
    }
}

如果您从自己的代码中删除了带有t的废话,它应该可以正常工作,但实现Runnable更具惯用性。线程已经设置为执行您尝试执行的操作。

答案 1 :(得分:0)

让ThreadDemo实现Runnable而不是扩展Thread。

添加将调用t.join()

的ThreadDemo.join()方法

研究Thread和Runnable javadocs。