小言_互联网的博客

Java-五种线程池,四种拒绝策略,三种阻塞队列

454人阅读  评论(0)

三种阻塞队列

BlockingQueue<Runnable> workQueue = null;

workQueue = new ArrayBlockingQueue<>(5);//基于数组的先进先出队列,有界

workQueue = new LinkedBlockingQueue<>();//基于链表的先进先出队列,无界

workQueue = new SynchronousQueue<>();//无缓冲的等待队列,无界

四种拒绝策略

RejectedExecutionHandler rejected = null;

rejected = new ThreadPoolExecutor.AbortPolicy();//默认,队列满了丢任务抛出异常

rejected = new ThreadPoolExecutor.DiscardPolicy();//队列满了丢任务不异常

rejected = new ThreadPoolExecutor.DiscardOldestPolicy();//将最早进入队列的任务删,之后再尝试加入队列

rejected = new ThreadPoolExecutor.CallerRunsPolicy();//如果添加到线程池失败,那么主线程会自己去执行该任务

如何创建线程池?

直接使用ThreadPoolExecutor类的构造方法就可以创建线程池。我们来看下构造参数:


  
  1. /**
  2. *  corePoolSize    核心线程数
  3. *  maximumPoolSize 最大线程数
  4. *  keepAliveTime   idle线程存活时间
  5. *  unit            上个参数的单位
  6. *  workQueue       线程对象的缓冲队列
  7. *  threadFactory   生成线程的工厂(可选
  8. *  handler         达到容量后的回调(可选)
  9. */
  10. public ThreadPoolExecutor(int corePoolSize,
  11.                               int maximumPoolSize,
  12.                               long keepAliveTime,
  13.                               TimeUnit unit,
  14.                               BlockingQueue<Runnable> workQueue,
  15.                               ThreadFactory threadFactory,
  16.                               RejectedExecutionHandler handler)

五种线程池

ExecutorService threadPool = null;

threadPool = Executors.newSingleThreadExecutor();//单线程的线程池,只有一个线程在工作,阻塞队列使用的是LinkedBlockingQueue

threadPool = Executors.newFixedThreadPool(3);//固定大小的线程池,阻塞队列使用的是LinkedBlockingQueue

threadPool = Executors.newCachedThreadPool();//有缓冲的线程池,线程数 JVM 控制,阻塞队列使用的是SynchronousQueue

threadPool = Executors.newScheduledThreadPool(2);//定时任务功能的线程池

threadPool = new ThreadPoolExecutor();//默认线程池,可控制参数比较多


  
  1. public  static  void main ( String[] args) throws  Exception {
  2.     testThreadPoolExecutor();
  3. }
  4. public  static  void testThreadPoolExecutor() throws  Exception {
  5.      //基础参数
  6.      int corePoolSize= 2; //最小活跃线程数
  7.      int maximumPoolSize= 5; //最大活跃线程数
  8.      int keepAliveTime= 5; //指定线程池中线程空闲超过 5s 后将被回收
  9.     TimeUnit unit = TimeUnit.SECONDS; //keepAliveTime 单位
  10.      //阻塞队列
  11.     BlockingQueue<Runnable> workQueue =  null;
  12.     workQueue =  new ArrayBlockingQueue<>( 5); //基于数组的先进先出队列,有界
  13.     workQueue =  new LinkedBlockingQueue<>(); //基于链表的先进先出队列,无界
  14.     workQueue =  new SynchronousQueue<>(); //无缓冲的等待队列,无界
  15.      //拒绝策略
  16.     RejectedExecutionHandler rejected =  null;
  17.     rejected =  new ThreadPoolExecutor.AbortPolicy(); //默认,队列满了丢任务抛出异常
  18.     rejected =  new ThreadPoolExecutor.DiscardPolicy(); //队列满了丢任务不异常
  19.     rejected =  new ThreadPoolExecutor.DiscardOldestPolicy(); //将最早进入队列的任务删,之后再尝试加入队列
  20.     rejected =  new ThreadPoolExecutor.CallerRunsPolicy(); //如果添加到线程池失败,那么主线程会自己去执行该任务
  21.      //使用的线程池
  22.     ExecutorService threadPool =  null;
  23.     threadPool = Executors.newCachedThreadPool(); //有缓冲的线程池,线程数 JVM 控制
  24.     threadPool = Executors.newFixedThreadPool( 3); //固定大小的线程池
  25.     threadPool = Executors.newScheduledThreadPool( 2);
  26.     threadPool = Executors.newSingleThreadExecutor(); //单线程的线程池,只有一个线程在工作
  27.     threadPool =  new ThreadPoolExecutor(
  28.             corePoolSize,
  29.             maximumPoolSize,
  30.             keepAliveTime,
  31.             unit,
  32.             workQueue,
  33.             rejected); //默认线程池,可控制参数比较多
  34.      //执行无返回值线程
  35.     TaskRunnable taskRunnable =  new TaskRunnable();
  36.     threadPool.execute(taskRunnable);
  37.      List<Future< String>> futres =  new ArrayList<>();
  38.      for( int i= 0;i< 10;i++) {
  39.          //执行有返回值线程
  40.         TaskCallable taskCallable =  new TaskCallable(i);
  41.         Future< String> future = threadPool.submit(taskCallable);
  42.         futres.add(future);
  43.     }
  44.      for( int i= 0;i<futres.size();i++){
  45.          String result = futres.get(i).get();
  46.         System.out.println(i+ " result = "+result);
  47.     }
  48. }
  49. /**
  50.     * 返回值的线程,使用 threadpool.execut() 执行
  51.     */
  52. public  static  class TaskRunnable implements Runnable{
  53.     @Override
  54.      public  void run() {
  55.          try {
  56.             Thread.sleep( 1000);
  57.         }  catch (InterruptedException e) {
  58.             e.printStackTrace();
  59.         }
  60.         System.out.println(Thread.currentThread().getName() +  " runnable result!");
  61.     }
  62. }
  63. /**
  64.     * 有返回值的线程,使用 threadpool.submit() 执行
  65.     */
  66. public  static  class TaskCallable implements Callable<String>{
  67.      public TaskCallable( int index){
  68.         this.i=index;
  69.     }
  70.      private  int i;
  71.     @Override
  72.      public  String call() throws  Exception {
  73.          int r =  new Random().nextInt( 5);
  74.          try {
  75.             Thread.sleep(r);
  76.         }  catch (InterruptedException e) {
  77.             e.printStackTrace();
  78.         }
  79.          //System.out.println("callable result!");
  80.          return Thread.currentThread().getName()+ " callable index="+i + ",sleep="+r;
  81.     }
  82. }

 

 


转载:https://blog.csdn.net/qq_17010193/article/details/114587375
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场