转自:https://blog.csdn.net/zzti_erlie/article/details/84926355
介绍
先看如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class Test {
static Thread thread1 = new Thread(()-> { System.out.println("thread1"); });
static Thread thread2 = new Thread(()-> { System.out.println("thread2"); });
static Thread thread3 = new Thread(()-> { System.out.println("thread3"); });
public static void main(String[] args) throws InterruptedException { thread1.start(); thread2.start(); thread3.start(); }
}
|
重复执行多次,发现输出并不是按照线程的启动顺序来执行。因为这个里面涉及到CPU对线程的调度问题。
如何让 thread1,thread2,thread3 顺序执行呢?
方法1
通过join方法去保证多线程顺序执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class Test {
static Thread thread1 = new Thread(()-> { System.out.println("thread1"); });
static Thread thread2 = new Thread(()-> { System.out.println("thread2"); });
static Thread thread3 = new Thread(()-> { System.out.println("thread3"); });
public static void main(String[] args) throws InterruptedException { thread1.start(); thread1.join(); thread2.start(); thread2.join(); thread3.start(); }
}
|
可以看到输出一直是如下
1 2 3 4 5 6
| thread1 thread2 thread3 1 2 3
|
join 是怎么实现这个功能的呢?
join 方法让主线程等待子线程结束以后才能继续运行,因此保证了线程的顺序执行
方法2
使用单例线程池,用唯一的工作线程执行任务,保证所有任务按照指定顺序执行
1
| ExecutorService executorService = Executors.newSingleThreadExecutor();
|
这个会把线程放在一个 FIFO 队列,依次执行线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class Test {
static Thread thread1 = new Thread(()-> { System.out.println("thread1"); });
static Thread thread2 = new Thread(()-> { System.out.println("thread2"); });
static Thread thread3 = new Thread(()-> { System.out.println("thread3"); });
static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[] args) throws InterruptedException { executorService.submit(thread1); executorService.submit(thread2); executorService.submit(thread3); executorService.shutdown(); }
}
|
输出一直为