join 当前线程等待子线程运行结束。
当前线程等待调用join方法的那个线程结束之后再执行。
在哪个区域里面new的Thread的,当前线程就是该区域所在的线程。
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
IntStream.range(1, 1000)
.forEach(i -> System.out.println(Thread.currentThread().getName() + "->" + i));
});
Thread t2 = new Thread(() -> {
IntStream.range(1, 1000)
.forEach(i -> System.out.println(Thread.currentThread().getName() + "->" + i));
});
t1.start();
t2.start();
t1.join();
t2.join();
Optional.of("All of tasks finish done.").ifPresent(System.out::println);
IntStream.range(1, 1000)
.forEach(i -> System.out.println(Thread.currentThread().getName() + "->" + i));
}
}
public class Test {
public static void main(String[] args) throws InterruptedException{
Thread t0 = new Thread(()->{
try {
Thread.sleep(3_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread t1 = new Thread(()->{
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t0.start();
t0.join();
}
}
public class Test1 {
public static void main(String[] args) throws InterruptedException {
Thread.currentThread().join();
}
}
|