join方法的作用是让一个线程等待另一个线程执行结束,再继续执行。
调用t.join的线程会被阻塞,一直阻塞到t线程执行结束为止。
1、主线程调用t.join,被阻塞
public class Demo {
public static void main(String[] args) {
Thread thread = new Thread(()->{
System.out.println("t1进行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread1.start();
System.out.println("t开始");
try {
thread1.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t结束");
}
}
2、t2调用t1.join,t2被阻塞
public class Demo {
public static void main(String[] args) {
Thread t1 = new Thread(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 5; i++) {
System.out.println("t1进行");
}
});
Thread t2 = new Thread(()->{
try {
t1.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 5; i++) {
System.out.println("t2进行");
}
});
t1.start();
t2.start();
System.out.println("main进行");
}
}
这里main线程未被阻塞,反而是t2线程被阻塞,说明调用t.join()方法的线程会被t线程阻塞
3、start和join的位置
只有当调用start之后,join 才会生效
public class Demo {
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
System.out.println("t1进行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread2 = new Thread(()->{
System.out.println("t2进行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread1.start();
try {
thread1.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
thread2.start();
try {
thread2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
执行结果如下
如果代码换一种写法
public class Demo {
public static void main(String[] args) {
Thread thread1 = new Thread(()->{
for (int i = 0; i < 5; i++) {
System.out.println("t1进行");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread2 = new Thread(()->{
for (int i = 0; i < 5; i++) {
System.out.println("t2进行");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread1.start();
thread2.start();
try {
thread1.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
thread2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
那么t1线程和t2线程的执行顺序依然是随机的