线程池
2018-10-27 本文已影响0人
笑才
1、关系简介
Executor(接口)-->ExecutorService(接口)-->AbstractExecutorService(抽象类) -->ThreadPoolExecutor(类)
2、ThreadPoolExecutor实现线程池
public class ThreadPoolTest01 {
public static void main(String[] args) {
//new ThreadPoolExecutor(核心线程数,最大线程数,线程存活时间,存活时间的单位,线程缓存队列,线程池拒绝策略);
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200L,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(5));
//ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200L,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(5),new ThreadPoolExecutor.DiscardPolicy());
for(int i =1;i<=20;i++){
MyThreadPool01 mythread = new MyThreadPool01(i);
executor.execute(mythread);//提交线程到线程池,并执行调度
System.out.println("线程池中线程数:"+executor.getPoolSize()+",队列中等待执行的任务数:"+executor.getQueue().size()+",已执行完的任务数:"+executor.getCompletedTaskCount());
}
executor.shutdown();//关闭线程池(等待缓存的所有线程执行完毕之后再关闭线程池),executor.shutdownNow(),这个是立即关闭线程池
}
}
class MyThreadPool01 implements Runnable{
private int i;
public MyThreadPool01(int i){
this.i = i;
}
public void run() {
System.out.println("正在执行任务:"+i);
try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
System.out.println("任务"+i+"执行完毕");
}
}
new ThreadPoolExecutor(核心线程数,最大线程数,线程存活时间,存活时间的单位,线程缓存队列,线程池拒绝策略);
线程缓存队列:ArrayBlockingQueue,创建时必须指定大小,LinkedBlockingQueue,synchronousQueue
线程池拒绝策略:ThreadPoolExecutor.AbortPolicy丢弃并抛出异常,ThreadPoolExecutor.DiscardPolicy丢弃不抛弃异常,ThreadPoolExecutor.DiscardOldestPolicy丢弃队列最前面的任务,然后重新尝试执行任务(重复此过程),ThreadPoolExecutor.CallerRunsPolicy由调用线程处理该任务
注意如果设置ThreadPoolExecutor.DiscardPolicy,ThreadPoolExecutor.DiscardOldestPolicy策略时,如果需要通过Future获取返回值,则会出现问题
3、Executors.newFixedThreadPool(5),Executors.newCachedThreadPool(),Executors.newSingleThreadExecutor()创建线程池(java doc中推荐池使用方式)
public class ThreadPoolTest02 {
public static void main(String[] args) {
//new ThreadPoolExecutor(核心线程数,最大线程数,线程存活时间,存活时间的单位,线程缓存队列,线程池拒绝策略);
//ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200L,TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(5));
ExecutorService executor = Executors.newFixedThreadPool(5);//创建固定容量大小的缓冲池
//Executors.newCachedThreadPool();创建一个缓冲池,缓冲池大小为Integer.MAX_VALUE
//Executors.newSingleThreadExecutor();创建一个容量为1的缓冲池
for(int i =1;i<=20;i++){
MyThreadPool02 mythread = new MyThreadPool02(i);
executor.execute(mythread);//提交线程到线程池,并执行调度
//executor.submit(mythread);有Future返回值
}
executor.shutdown();//关闭线程池(等待缓存的所有线程执行完毕之后再关闭线程池),executor.shutdownNow(),这个是立即关闭线程池
}
}
class MyThreadPool02 implements Runnable{
private int i;
public MyThreadPool02(int i){
this.i = i;
}
public void run() {
System.out.println("正在执行任务:"+i);
try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}
System.out.println("任务"+i+"执行完毕");
}
}