标签:线程 over private 方法注释 code int 结果 stack div
当在一个线程中调用另一个线程的join()方法时,当前线程转入阻塞状态,等待另一个线程执行结束后再继续执行当前线程。
示例:
public class ThreadJoinDemo { public static void main(String[] args) throws InterruptedException { System.out.println("Main Thread start!"); Thread1 thread1 = new Thread1("A"); Thread thread2 = new Thread1("B"); thread1.start(); thread2.start(); //此处不添加join方法,则主线程会先结束,然后A、B线程结束 //添加join方法后,主线程会在A、B线程结束后再结束 thread1.join(); thread2.join(); System.out.println("Main Thread end!"); } static class Thread1 extends Thread { private String name; public Thread1(String name) { super(name); this.name = name; } @Override public void run() { System.out.println(Thread.currentThread().getName() + " start"); for (int i = 0; i < 5; i ++) { System.out.println("子线程" + name + "run:" + i); try { sleep((long) (Math.random() * 10)); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + " end"); } } }
如果把join方法注释掉,则结果如下,主线程先结束,然后线程A、B结束:
Main Thread start! A start 子线程Arun:0 Main Thread end! B start 子线程Brun:0 子线程Brun:1 子线程Arun:1 子线程Arun:2 子线程Brun:2 子线程Brun:3 子线程Brun:4 子线程Arun:3 B end 子线程Arun:4 A end
join方法放开的话,则主线程会等A、B线程结束后再结束:
Main Thread start! A start 子线程Arun:0 B start 子线程Brun:0 子线程Arun:1 子线程Brun:1 子线程Brun:2 子线程Arun:2 子线程Brun:3 子线程Arun:3 子线程Arun:4 A end 子线程Brun:4 B end Main Thread end!
标签:线程 over private 方法注释 code int 结果 stack div
原文地址:https://www.cnblogs.com/snowcity1231/p/10480177.html