ThreadPoolExecutor参数介绍
1、corePoolSize:核心线程数,核心线程会一直存活,即使没有任务
2、maximumPoolSize:线程池中的最大线程数
3、workQueue:阻塞队列的容量,用来存储等待执行的任务
4、keepAliveTime:线程空闲时间
5、ThreadFactory:线程工厂
5、RejectedExecutionHandler:拒绝策略
6、TimeUnit 时间单位
提交任务的方式
- execute
- submit
两者的区别是execute方法用于提交不需要返回值的任务,submit用于提交需要返回值或者执行状态的任务
提交任务种类
- Runnable
- Callable
区别:Runnable 不会返回结果,并且无法抛出经过检查的异常
代码实现
public class ThreadPoolTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//阻塞队列
BlockingQueue bq = new ArrayBlockingQueue(2);
//线程工厂
ThreadFactory factory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
};
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 60, TimeUnit.SECONDS,bq,factory,new ThreadPoolExecutor.CallerRunsPolicy());
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"sss");
}
});
Future<?> ft = threadPoolExecutor.submit(new Runnable() {
@Override
public void run() {
System.out.println("zhe gai zen me ban");
int a = 1;
}
});
try{Thread.sleep(100);}catch (Exception e){}
System.out.println(ft.isDone());
Future<Object> submit = threadPoolExecutor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
return "小猪佩奇";
}
});
try{Thread.sleep(1000);}catch (Exception e){}
System.out.println(submit.get());
}
}
网友评论