个人心得|如何控制多线程的执行顺序

多线程的执行顺序,在下进来了解了一点
先来原来的没有排序的线程是怎么样的

public class App {staticThread thread1 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread1"); } }); staticThread thread2 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread2"); } }); staticThread thread3 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread3"); } }); static ExecutorService executorService = Executors.newSingleThreadExecutor(); public static void main(String[] args) throws InterruptedException { //join:让主线程等待子线程结束以后才能继续运行 System.out.println("Hello World"); thread1.start(); thread2.start(); thread3.start(); } }

结果是
个人心得|如何控制多线程的执行顺序
文章图片

然后第一种是join:
public class App {staticThread thread1 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread1"); } }); staticThread thread2 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread2"); } }); staticThread thread3 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread3"); } }); static ExecutorService executorService = Executors.newSingleThreadExecutor(); public static void main(String[] args) throws InterruptedException { //join:让主线程等待子线程结束以后才能继续运行 System.out.println("Hello World"); thread1.start(); thread1.join(); thread2.start(); thread1.join(); thread3.start(); }}

然后结果个人心得|如何控制多线程的执行顺序
文章图片

第二种是用了
ExecutorService executorService = Executors.newSingleThreadExecutor();

public class App {staticThread thread1 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread1"); } }); staticThread thread2 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread2"); } }); staticThread thread3 =new Thread(new Runnable(){ @Override public void run() { System.out.println("thread3"); } }); static ExecutorService executorService = Executors.newSingleThreadExecutor(); public static void main(String[] args) throws InterruptedException { //join:让主线程等待子线程结束以后才能继续运行 /*System.out.println("Hello World"); thread1.start(); thread1.join(); thread2.start(); thread1.join(); thread3.start(); */ executorService.submit(thread1); executorService.submit(thread2); executorService.submit(thread3); executorService.shutdown(); }}

【个人心得|如何控制多线程的执行顺序】

    推荐阅读