如何控制多线程执行顺序
package com.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 如何控制多线程执行顺序 * 1、join方法,让主线程等待子线程执行完后再执行 * 2、newSingleThreadExecutor,创建执行单个任务的线程池执行、保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行 */ public class ThreadFIFO { public static void main(String[] args) { thread1(); thread2(); } public static void thread2() { Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("thread1"); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { System.out.println("thread2"); } }); Thread thread3 = new Thread(new Runnable() { @Override public void run() { System.out.println("thread3"); } }); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(thread1); executorService.submit(thread2); executorService.submit(thread3); executorService.shutdown(); } public static void thread1() { Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("thread1"); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { System.out.println("thread2"); } }); Thread thread3 = new Thread(new Runnable() { @Override public void run() { System.out.println("thread3"); } }); try { // join 让主线程等待子线程执行完后再执行 thread1.start(); thread1.join(); thread2.start(); thread2.join(); thread3.start(); thread3.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }