欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jdk自带的线程池

程序员文章站 2022-04-03 14:54:46
...

public class ThreadPool {

 public static void main(String[] args) {
  /*
  //线程池
  int corePoolSize = 2;
  int maximumPoolSize = 5;
  long keepAliveTime = 0;
  TimeUnit unit = TimeUnit.SECONDS;
  BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(8);
//  ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize,
//                maximumPoolSize,
//                keepAliveTime,
//                unit,
//                workQueue);
//  for(int i=0;i<25;i++)
//  pool.submit(new PrintThread());
//  pool.shutdown();

  //拒绝策略:中止
  keepAliveTime = 30;
  ThreadPoolExecutor pool2 = null;
  try {
   pool2= new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
    Executors.defaultThreadFactory(), new AbortPolicy());
  for(int i=0;i<25;i++)
   pool2.submit(new PrintThread());
  }finally {
   pool2.shutdown();
  }
  */
  //单个线程:一个一个地执行
//  ExecutorService e = Executors.newSingleThreadExecutor();
//  Executors.newSingleThreadExecutor(threadFactory);
//  for(int i=0;i<10;i++) {
//   e.execute(new PrintThread());
//  }
//  e.shutdown();
  
  //固定线程池:3个工作线程
//  ExecutorService e = Executors.newFixedThreadPool(3);
//  for(int i=0;i<10;i++)
//   e.execute(new PrintThread());
//  e.shutdown();
  
  //需要多少线程就创建多少
//  ExecutorService e = Executors.newCachedThreadPool();
//  for(int i=0;i<1000;i++)
//   e.execute(new PrintThread());
//  e.shutdown();
  
  //定时任务:单线程
//  ScheduledExecutorService e = Executors.newSingleThreadScheduledExecutor();
//  e.schedule(new PrintThread(), 10, TimeUnit.SECONDS); //延迟10秒执行一次
//  e.schedule(new PrintThread(), 10, TimeUnit.SECONDS);
//  e.scheduleWithFixedDelay(new PrintThread(), 2, 12, TimeUnit.SECONDS); //每隔12秒执行一次
  
  //定时任务:三个线程并发执行
  ScheduledExecutorService e = Executors.newScheduledThreadPool(3);
  for(int i=0;i<4;i++)
   e.scheduleWithFixedDelay(new PrintThread(), 2, 5, TimeUnit.SECONDS); //每隔5秒执行一次
  
  e.scheduleAtFixedRate(new PrintThread(), 2, 6, TimeUnit.SECONDS); //每隔6执行一次
  
 }
 
 static class PrintThread implements Runnable{

  public void run() {

   System.out.println("hello..");
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 

}

相关标签: 线程池