java 中Thread.join()的使用方法
程序员文章站
2024-03-02 23:56:28
java 中thread.join()的使用方法
如果一个线程a执行了thread.join()语句,其含义是:当前线程a等待thread线程终止之后才从thread.j...
java 中thread.join()的使用方法
如果一个线程a执行了thread.join()语句,其含义是:当前线程a等待thread线程终止之后才从thread.join()返回。
import java.util.concurrent.timeunit; /** * 6-13 */ public class join { public static void main(string[] args) throws exception { thread previous = thread.currentthread(); for (int i = 0; i < 10; i++) { // 每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回 thread thread = new thread(new domino(previous), string.valueof(i)); thread.start(); previous = thread; } timeunit.seconds.sleep(5); system.out.println(thread.currentthread().getname() + " terminate."); } static class domino implements runnable { private thread thread; public domino(thread thread) { this.thread = thread; } public void run() { try { thread.join(); } catch (interruptedexception e) { } system.out.println(thread.currentthread().getname() + " terminate."); } } }
执行结果:
main terminate. 0 terminate. 1 terminate. 2 terminate. 3 terminate. 4 terminate. 5 terminate. 6 terminate. 7 terminate. 8 terminate. 9 terminate.
下一篇: Java代码生成器