线程池

/*

 * 线程池

 */

public classThreadPoolTest {

   public static voidmain(String[] args) throws InterruptedException{

      /*

       * 查看源码不难发现这些线程池都是通过ThreadPoolExecutor实现的,可以用ThreadPoolExecutor自定义线程池

       */

      /*

       *newFixedThreadPool(n),该该方法创建一个固定数量的线程池,

       * 线程数始终不变,当有一个任务提交时,若线程池中空闲,则立即执行,若没有空闲线程,则会被暂缓在一个任务队列中等待有空闲的线程去执行

       * 底层实现: ThreadPoolExecutor(10, 10,0L, TimeUnit.MILLISECONDS,new

       * LinkedBlockingQueue<Runnable>());存活0L,也就是执行完毕,立即回收。

       */

      ExecutorService fixedTreadPool =Executors.newFixedThreadPool(10);

      /*

       * 创建一个线程的线程池,若空闲则执行,若没有空闲线程则暂缓在任务队列中底层实现: newThreadPoolExecutor(1,

       *1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())

       */

      ExecutorService singleThreadExecutor =Executors.newSingleThreadExecutor();

      /*

       * 带缓存的线程池:创建一个可根据实际情况调整线程个数的线程池,不限制最大线程数,若有

       * 空闲线程,则执行任务。若无任务则不创建线程,并且每个空闲线程会在60s后自动回收。底层实现: ThreadPoolExecutor(0,

       *Integer.MAX_VALUE,60L, TimeUnit.SECONDS, new

       *SynchronousQueue<Runnable>()) Integer.MAX_VALUE表示不限制容量 60L表示存活60,单位为

       *TimeUnit.SECONDS SynchronousQueue队列,无容量队列,底层实现,应该是一个take方法阻塞者,

       *add一个就立刻提交给take方法。假设存活60s,在第59秒突然有任务来了,则直接执行任务,空闲60s则回收

       */

      ExecutorService cachedTreadPool =Executors.newCachedThreadPool();

      /*

       * 该方法返回一个SchededExecutorService对象,但该线程池可以指定线程的数量

       * 稍微麻烦一点,多次调用之后,还是调用ThreadPoolExecutor()方法,内部采用了DelayedWorkQueue队列

       *DelayedWorkQueue队列会在时间到了之后,从队列中移除。

       */

      ScheduledExecutorService scheduledThreadPool =Executors.newScheduledThreadPool(10);

      // 模拟定时器,3秒执行一次.类似java中的timer

      /*

       *scheduleWithFixedDelay(Runnable command, 命令 long initialDelay,

       * 初始化时间,1秒后初始化 longdelay, 轮询时间 TimeUnit unit) 单位

       */

      scheduledThreadPool.scheduleWithFixedDelay(newCommand(), 1, 3, TimeUnit.SECONDS);

   }

}

 

class Command implements Runnable{

 

   @Override

   public void run() {

      System.out.println("task");

   }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值