s-day06-线程池:处理runnable任务
This commit is contained in:
@@ -27,6 +27,18 @@ ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
|
||||
|
||||
2.什么时候会开始拒绝任务???
|
||||
当所有的核心线程和临时线程都在忙,而且任务对列也都满了,新的任务还来,线程池就开始拒绝任务
|
||||
----------------------------------------------------------
|
||||
常用的API
|
||||
void execute(Runnable command) 在将来某个时候执行给定的任务。
|
||||
<T> Future<T> submit(Callable<T> task) 提交值返回任务以执行,并返回代表任务待处理结果的Future。
|
||||
void shutdown() 启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务。
|
||||
List<Runnable> shutdownNow() 尝试停止所有主动执行的任务,停止等待任务的处理,并返回正在等待执行的任务列表。
|
||||
|
||||
-----------------------------------------------------------------
|
||||
AbortPolicy:当线程池添加超负荷任务时,直接抛异常(默认策略)
|
||||
DiscardOldestPolicy:丢弃任务,但不抛异常,不推荐
|
||||
CallerRunsPolicy:由主线程负责调用任务的run方法
|
||||
DiscardPolicy:也是直接丢弃
|
||||
*/
|
||||
public class Demo12 {
|
||||
public static void main(String[] args) {
|
||||
@@ -40,5 +52,27 @@ public class Demo12 {
|
||||
Executors.defaultThreadFactory(),
|
||||
new ThreadPoolExecutor.AbortPolicy()
|
||||
);
|
||||
//创建任务交给线程池处理
|
||||
Task task = new Task();
|
||||
threadpool.execute(task);
|
||||
threadpool.execute(task);
|
||||
threadpool.execute(task);//3个核心线程都已经被占用,给4个任务队列,排队
|
||||
threadpool.execute(task);
|
||||
threadpool.execute(task);
|
||||
threadpool.execute(task);
|
||||
threadpool.execute(task);//4个任务队列都满了,创建2个临时线程
|
||||
threadpool.execute(task);
|
||||
threadpool.execute(task);
|
||||
//--------------------------------
|
||||
try{
|
||||
//第10个任务,核心线程,临时线程都在干活,任务队列也满了,此时开始拒绝策略
|
||||
threadpool.execute(task);
|
||||
}catch (RejectedExecutionException e){
|
||||
System.out.println("任务被拒绝执行");
|
||||
}
|
||||
|
||||
threadpool.shutdown();//有序停止,等待所有线程干完活
|
||||
// threadpool.shutdownNow();
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.inmind.threadpool10;
|
||||
//线程任务!!!
|
||||
public class Task implements Runnable{
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println(Thread.currentThread().getName()+"正在执行任务");
|
||||
try {
|
||||
Thread.sleep(10000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user