关于在订单中加入线程

时间:2013-02-18 17:02:05

标签: java multithreading

我是线程世界的新bie,还在学习,因为我正在经历线程的概念并加入其他线程等待早期线程完成的地方并从那个端点加入它,你能告诉我吗?我希望启动三个线程T1,T2,T3,其中t2将在T1完成后启动。

3 个答案:

答案 0 :(得分:2)

我理解你要等到线程1完全完成然后启动线程2,而线程3可以在任何地方运行。我认为简单的代码可以解决您的问题:

Thread thread1 = new Thread1();
Thread thread2 = new Thread2();
Thread thread3 = new Thread3();
thread3.start();
thread1.start();
try {
  thread1.join();
  thread2.start();
} catch (InterruptedException e) {
  //if you do not use thread1.interrupt() this will not happen.
}

答案 1 :(得分:0)

你可以使用Barriers在一些线程完成后开始一些动作(可能是另一个线程)。

检查:http://programmingexamples.wikidot.com/java-barrier了解详情。

但是等待只有一个线程真的没有多大意义......

答案 2 :(得分:0)

做这样的事情:

        Thread T1 = new Thread(new ThreadExm);  // where ThreadExm implements Runnable
        Thread T2 = new Thread(new ThreadExm);

        try {
            // Start the thread1 and waits for this thread to die before
            // starting the thread2 thread.
            T1.start();
            T2.join();

            // Start thread2 when T1 gets completed
            thread2.start();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }