进阶day06-线程池:处理runnable任务

This commit is contained in:
2026-03-10 10:23:03 +08:00
parent a996cfdb1a
commit 7bdd904e54
2 changed files with 76 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
package com.inmind.thread_pool10;
import java.util.concurrent.*;
/*
学习内容线程池处理runnable任务
常用的API
void execute(Runnable command) 在将来某个时候执行给定的任务。
<T> Future<T> submit(Callable<T> task) 提交值返回任务以执行并返回代表任务待处理结果的Future。
void shutdown() 启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务。
List<Runnable> shutdownNow() 尝试停止所有主动执行的任务,停止等待任务的处理,并返回正在等待执行的任务列表。
注意:
1.临时线程什么时候会创建??
新任务提交到线程池,发现所有的核心线程都被占用,任务队列也满了,并且还可以创建临时线程时,才会创建新的临时线程
2.什么时候会开始拒绝任务???
当所有的核心线程和临时线程都在忙,而且任务队列也都满了,新的任务还来,线程池就开始拒绝任务
---------------------------------------
线程池超负荷运行任务策略:
AbortPolicy当线程池添加超负荷任务时直接抛异常默认策略
DiscardOldestPolicy丢弃任务但不抛异常不推荐
CallerRunsPolicy由主线程负责调用任务的run方法
DiscardPolicy也是直接丢弃
*/
public class Demo11 {
public static void main(String[] args) {
//使用多态创建线程池对象
ExecutorService threadPool = new ThreadPoolExecutor(
3,
5,
8,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(4),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy());
//创建出任务
MyRunnable task = new MyRunnable();
//将任务交给线程池处理
threadPool.execute(task);
threadPool.execute(task);
threadPool.execute(task);
//核心线程占满,将任务放入到任务队列
threadPool.execute(task);
threadPool.execute(task);
threadPool.execute(task);
threadPool.execute(task);
//线程任务长时间占用3个核心线程4个任务队列也排满了此时创建临时线程2个
threadPool.execute(task);
threadPool.execute(task);
//所有的核心线程和临时线程都在忙,而且任务队列也都满了,如果还来任务,就要执行对应的策略
threadPool.execute(task);
System.out.println("程序结束");
//将线程池关闭
// threadPool.shutdown();//启动有序关闭,其中先前提交的任务将被执行,但不会再接收新的任务
threadPool.shutdownNow();//尝试停止所有正在执行的任务,并返回正在等待执行的任务列表
}
}

View File

@@ -0,0 +1,13 @@
package com.inmind.thread_pool10;
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行了任务");
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}