join的作用
当我们调用某个线程的这个方法时,这个方法会挂起调用线程,直到被调用线程结束执行,调用线程才会继续执行
join()
public class ThreadJoin {
public static void main(String[] args) {
Thread t1 =
new Thread(
() -> {
IntStream.range(1, 100)
.forEach(i -> System.out.println(
Thread.currentThread().getName() + "->" + i));
});
Thread t2 =
new Thread(
() -> {
IntStream.range(1, 100)
.forEach(i -> System.out.println(
Thread.currentThread().getName() + "->" + i));
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Optional.of("all tasks finished").ifPresent(System.out::println);
IntStream.range(1, 100)
.forEach(i -> System.out.println(
Thread.currentThread().getName() + "->" + i));
}
/**
* 如果没有join,t1和main交互执行
* Thread-0->1
* main->1
* Thread-0->2
* main->2
* main->3
*
* t1、t2加入join会交替执行,因为是多线程,不是单线程,但是main会等到t1、t2都结束后再执行
* 加入join 被调用(t1、t2)线程执行结束后,才执行调用(main)线程
* */
}
join(long millis, int nanos)
public class ThreadJoin1 {
public static void main(String[] args) {
Thread t1 =
new Thread(
() -> {
try {
System.out.println("t1 is running");
Thread.sleep(10_000);
System.out.println("t1 is done");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
try {
// 如果t1在100毫秒没执行完,10纳秒之后main线程开始执行
t1.join(100,10);
} catch (InterruptedException e) {
e.printStackTrace();
}
IntStream.range(1, 100)
.forEach(i -> System.out.println(
Thread.currentThread().getName() + "->" + i));
}
}