join() :Waits for this thread to die.等待此线程结束
join(long millis): Waits at most milliseconds for this thread to die. A timeout of 0 means to wait forever.设置加入的线程超时时间,0代表永久等待
Thread类的join方法是等待join的线程结束,然后再执行自身的线程。
/**
*假如有a、b、c三个线程安装顺序执行
*/
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A");});
Thread b = new Thread(() -> {
try {
a.join();
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");});
Thread c = new Thread(() -> {
try {
b.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("C");});
c.start();
b.start();
a.start();
}
}
通过创建单个线程的线程池的方式,将线程放在一个队列中实现顺序执行。
public class ThreadFactoryTest {
public static void main(String[] args) {
ExecutorService ex = Executors.newSingleThreadExecutor();
ex.execute(() -> System.out.println("A"));
ex.execute(() -> System.out.println("B"));
ex.execute(() -> System.out.println("C"));
ex.shutdown();
}
}
原文:https://www.cnblogs.com/Nilekai/p/14315081.html