s-day06--线程池的概念与操作
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
package com.inmind.thread_pool08;
|
||||
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/*
|
||||
在java中使用一个接口表示线程池ExecutorService
|
||||
如何获取线程池对象??
|
||||
方式一:直接创建实现类ThreadPoolExecutor 的对象
|
||||
方式二:Executors(线程池)的静态方法
|
||||
|
||||
方式一的构造方法:
|
||||
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
|
||||
TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
|
||||
|
||||
参数一:corePoolSize,指定线程池核心线程的数量
|
||||
参数二:maximumPoolSize,指定线程池的最大线程数量
|
||||
参数三:keepAliveTime,指定临时线程的存活时间
|
||||
参数四:unit,指定临时线程存活时间单位(秒,分,时,天)
|
||||
参数五:workQueue 指定线程池的任务队列
|
||||
参数六:threadFactory,指定线程池的线程工厂
|
||||
参数七:handler,指定线程池的任务拒绝策略
|
||||
|
||||
|
||||
注意:
|
||||
1.临时线程什么时候会创建??
|
||||
新任务提交到线程池,发现所有的核心线程都被占用,任务队列也满了,并且还可以创建临时线程时,才会创建新的临时线程
|
||||
|
||||
2.什么时候回开始拒绝任务???
|
||||
当所有的核心线程和临时线程都在忙,而且任务对了也都满了,新的任务还来,线程池就开始拒绝任务
|
||||
|
||||
-------------------------------------------------------------------------------------------
|
||||
常用的API
|
||||
void execute(Runnable command) 在将来某个时候执行给定的任务。
|
||||
<T> Future<T> submit(Callable<T> task) 提交值返回任务以执行,并返回代表任务待处理结果的Future。
|
||||
void shutdown() 启动有序关闭,其中先前提交的任务将被执行,但不会接受任何新任务。
|
||||
List<Runnable> shutdownNow() 尝试停止所有主动执行的任务,停止等待任务的处理,并返回正在等待执行的任务列表。
|
||||
|
||||
*/
|
||||
public class Demo08 {
|
||||
public static void main(String[] args) {
|
||||
ExecutorService threadPool = new ThreadPoolExecutor(
|
||||
3,
|
||||
5,
|
||||
8,
|
||||
TimeUnit.SECONDS,
|
||||
new ArrayBlockingQueue<>(4),
|
||||
Executors.defaultThreadFactory(),
|
||||
new ThreadPoolExecutor.AbortPolicy());
|
||||
|
||||
System.out.println(threadPool);
|
||||
//创建任务
|
||||
Task task = new Task();
|
||||
//让线程池执行任务
|
||||
threadPool.execute(task);
|
||||
threadPool.execute(task);
|
||||
threadPool.execute(task);
|
||||
//线程任务长时间占用,将任务放入任务队列
|
||||
threadPool.execute(task);
|
||||
threadPool.execute(task);
|
||||
threadPool.execute(task);
|
||||
threadPool.execute(task);
|
||||
//任务队列满了,那就创建临时线程
|
||||
threadPool.execute(task);
|
||||
threadPool.execute(task);
|
||||
//线程池已经是极限状态,再来一个任务就拒绝策略
|
||||
threadPool.execute(task);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.inmind.thread_pool08;
|
||||
|
||||
public class Task implements Runnable{
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println(Thread.currentThread().getName() + "正在执行任务");
|
||||
try {
|
||||
Thread.sleep(20000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user