package com.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 如何控制多線程執行順序 * 一、join方法,讓主線程等待子線程執行完後再執行 * 二、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(); } } }