主要两种思路:
创建方式有7种:
public class TreadPoolDemo3{
public static void main(String[] args){
ExecutorService threadPool = Exectors.newFixedThreadPool(2);
//添加任务方式 1
threadPool.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
//添加任务方式2
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
}
输出:
pool-1-thread-1
pool-1-thread-2
a.线程池返回结果
public class ThreadPoolDemo4 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(2);
//执行任务
Future<Integer> result = threadPool.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(10);
System.out.println("随机数" + num);
return num;
}
});
//打印线程池返回方式
System.out.println("返回结果:" + result.get());
}
}
输出
随机数8
返回结果:8
b.⾃定义线程池名称或优先级
public class ThreadPoolDemo5 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建线程工厂
ThreadFactory threadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
//!!!!!!!一定要注意:要把任务Runnable设置给新创建的线程
Thread thread = new Thread(r);
//设置线程的命名规则
thread.setName("我的线程" + r.hashCode());
//设置线程的优先级
thread.setPriority(Thread.MAX_PRIORITY);
return thread;
}
};
ExecutorService threadPool = Executors.newFixedThreadPool(2,threadFactory);
//执行任务1
Future<Integer> result = threadPool.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(10);
System.out.println(Thread.currentThread().getPriority() + ", 随机数:" + num);
return num;
}
});
//打印线程池返回结果
System.out.println("返回结果:" + result.get());
}
}
public class ThreadPoolDemo6 {
public static void main(String[] args) {
//创建线程池
ExecutorService service = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
int finalI = i;
service.submit(() -> {
System.out.println("i : " + finalI + "|线程名称:" + Thread.currentThread().getName());
});
}
}
}
输出
i : 1|线程名称:pool-1-thread-2
i : 4|线程名称:pool-1-thread-5
i : 3|线程名称:pool-1-thread-4
i : 5|线程名称:pool-1-thread-6
i : 0|线程名称:pool-1-thread-1
i : 2|线程名称:pool-1-thread-3
i : 6|线程名称:pool-1-thread-7
i : 7|线程名称:pool-1-thread-8
i : 8|线程名称:pool-1-thread-9
i : 9|线程名称:pool-1-thread-1
优点:线程池会根据任务数量创建线程池,并且在一定时间内可以重复使用这些线程,产生相应的线程池。
缺点:适用于短时间有大量任务的场景,它的缺点是可能会占用很多的资源。
a.延迟执⾏(⼀次)
public class ThreadPoolDemo7 {
public static void main(String[] args) {
//创建线程池
ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
System.out.println("添加任务的时间:" + LocalDateTime.now());
//执行定时任务(延迟3s执行)只执行一次
service.schedule(new Runnable() {
@Override
public void run() {
System.out.println("执行子任务:" + LocalDateTime.now());
}
},3, TimeUnit.SECONDS);
}
}
输出
添加任务的时间:2022-04-13T14:19:39.983
执行子任务:2022-04-13T14:19:42.987
b. 固定频率执⾏
public class ThreadPoolDemo8 {
public static void main(String[] args) {
//创建线程池
ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
System.out.println("添加任务时间:" + LocalDateTime.now());
//2s之后开始执行定时任务,定时任务每隔4s执行一次
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("执行任务:" + LocalDateTime.now());
}
},2,4, TimeUnit.SECONDS);
}
}
输出
添加任务时间:2022-04-13T14:24:38.810
执行任务:2022-04-13T14:24:40.814
执行任务:2022-04-13T14:24:44.814
执行任务:2022-04-13T14:24:48.813
执行任务:2022-04-13T14:24:52.815
执行任务:2022-04-13T14:24:56.813
执行任务:2022-04-13T14:25:00.813
执行任务:2022-04-13T14:25:04.814
执行任务:2022-04-13T14:25:08.813
... ...
... ...
执行任务:2022-04-13T14:26:44.814
执行任务:2022-04-13T14:26:48.813```
注意事项:
public class ThreadPoolDemo9 {
public static void main(String[] args) {
//创建线程池
ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
System.out.println("添加任务时间:" + LocalDateTime.now());
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("执行任务: " + LocalDateTime.now());
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},2,4, TimeUnit.SECONDS);
}
}
输出
添加任务时间:2022-04-13T14:33:34.551
执行任务: 2022-04-13T14:33:36.556
执行任务: 2022-04-13T14:33:41.557
执行任务: 2022-04-13T14:33:46.559
执行任务: 2022-04-13T14:33:51.561
执行任务: 2022-04-13T14:33:56.562
执行任务: 2022-04-13T14:34:01.564
执行任务: 2022-04-13T14:34:06.566
执行任务: 2022-04-13T14:34:11.566
执行任务: 2022-04-13T14:34:16.567
执行任务: 2022-04-13T14:34:21.570
执行任务: 2022-04-13T14:34:26.570
... ....
c.scheduleAtFixedRate VS scheduleWithFixedDelay
scheduleAtFixedRate 是以上⼀次任务的开始时间,作为下次定时任务的参考时间的(参考时间+延迟任务=任务执⾏)。scheduleWithFixedDelay 是以上⼀次任务的结束时间,作为下次定时任务的参考时间的。
public class ThreadPoolDemo10 {
public static void main(String[] args) {
//创建线程池
ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
System.out.println("添加任务时间:" + LocalDateTime.now());
//2s之后开始执行定时任务,定时任务每隔4s执行一次
service.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println("执行任务:" + LocalDateTime.now());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 2, 4, TimeUnit.SECONDS);
}
}
输出
添加任务时间:2022-04-13T14:46:02.871
执行任务:2022-04-13T14:46:04.876
执行任务:2022-04-13T14:46:09.878
执行任务:2022-04-13T14:46:14.880
执行任务:2022-04-13T14:46:19.883
执行任务:2022-04-13T14:46:24.885
执行任务:2022-04-13T14:46:29.888
执行任务:2022-04-13T14:46:34.888
执行任务:2022-04-13T14:46:39.891
执行任务:2022-04-13T14:46:44.893
执行任务:2022-04-13T14:46:49.895
执行任务:2022-04-13T14:46:54.897
执行任务:2022-04-13T14:46:59.900
执行任务:2022-04-13T14:47:04.901
... ...
public class ThreadPoolDemo11 {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
System.out.println("添加任务的时间:" + LocalDateTime.now());
service.schedule(new Runnable() {
@Override
public void run() {
System.out.println("执行时间:" + LocalDateTime.now());
}
},2, TimeUnit.SECONDS );
}
}
输出
添加任务的时间:2022-04-13T15:06:38.100
执行时间:2022-04-13T15:06:40.106
public class ThreadPoolDemo12 {
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadScheduledExecutor();
for (int i = 0; i < 10; i++) {
service.submit(new Runnable() {
@Override
public void run() {
System.out.println("线程名:" + Thread.currentThread().getName());
}
});
}
}
}
输出
线程名:pool-1-thread-1
线程名:pool-1-thread-1
线程名:pool-1-thread-1
线程名:pool-1-thread-1
线程名:pool-1-thread-1
线程名:pool-1-thread-1
线程名:pool-1-thread-1
线程名:pool-1-thread-1
线程名:pool-1-thread-1
线程名:pool-1-thread-1
public class ThreadPoolDemo13 {
public static void main(String[] args) {
ExecutorService service = Executors.newWorkStealingPool();
for (int i = 0; i < 10; i++) {
service.submit(() -> {
System.out.println("线程名" + Thread.currentThread().getName());
});
while(!service.isTerminated()) {
}
}
}
}
输出
线程名ForkJoinPool-1-worker-1
public class ThreadPoolDemo14 {
public static void main(String[] args) {
ThreadFactory factory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
return thread;
}
};
// 手动创建线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 100, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1), new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 4; i++) {
int finalI = i;
executor.submit(() -> {
System.out.println(Thread.currentThread().getName() + "执行任务:" + finalI);
});
}
//终止线程
executor.shutdown();
}
}
输出
main执行任务:2
pool-1-thread-1执行任务:0
main执行任务:3
pool-1-thread-1执行任务:1