一、使用线程池实现
使用线程池工具Executors.newSingleThreadExecutor(); 获得的是核心线程数量是1,最大线程数也是1,无界阻塞队列,
实际不建议使用Executors提供的工具,自己根据实际情况自定义线程池比较好。
实现线程顺序执行,我将线程放到我们定义好的线程池就好,线程池会按照我们提交的顺序执行我们递交的任务。
实例代码如下:
public static void main(String[] args) {
System.out.println("指定执行顺序:线程02,线程01,线程03");
//指定线程执行顺序
Thread thread01 = new Thread(() -> {
System.out.println("thread01执行");
});
Thread thread02 = new Thread(() -> {
System.out.println("thread02执行");
});
Thread thread03 = new Thread(() -> {
System.out.println("thread03执行");
});
/**
* ================
* 使用线程池指定线程执行顺序
*/
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(thread02);
executorService.submit(thread01);
executorService.submit(thread03);
}
二、使用join让线程等待
public static void main(String[] args) {
System.out.println("指定执行顺序:线程02,线程01,线程03");
//指定线程执行顺序
Thread thread01 = new Thread(() -> {
System.out.println("thread01执行");
});
Thread thread02 = new Thread(() -> {
System.out.println("thread02执行");
});
Thread thread03 = new Thread(() -> {
System.out.println("thread03执行");
});
/**
* =====================
* join执行线程执行顺序
*/
try {
thread02.start();
thread02.join();
thread01.start();
thread01.join();
thread03.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
3.使用计数器CountDownLatch
CountDownLatch提供了await让线程等待,当计数数值等于0时,线程开始执行
package com.goujia.springboot.test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* java类简单作用描述
*
* @ProjectName: springboot
* @Description:
* @Author: 洪建雄
* @CreateDate: 2019/9/27 0027 13:48
* @Version:
*/
public class ThreadOrderDemo {
public static void main(String[] args) {
CountDownLatch countDownLatch01 = new CountDownLatch(1);
CountDownLatch countDownLatch02 = new CountDownLatch(1);
System.out.println("指定执行顺序:线程02,线程01,线程03");
//指定线程执行顺序
Thread thread01 = new Thread(() -> {
try {
countDownLatch01.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread01执行");
countDownLatch02.countDown();
});
Thread thread02 = new Thread(() -> {
System.out.println("thread02执行");
countDownLatch01.countDown();
});
Thread thread03 = new Thread(() -> {
try {
countDownLatch02.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread03执行");
});
/**
* ==============
* 使用CountDownLatch执行线程执行顺序
*/
thread01.start();
thread02.start();
thread03.start();
}
}