android 四种线程池的使用

本文为转载文章:原文章请点击

线程有哪些种类?

      (1)newFixedThreadPool

        该模式全部由核心线程去实现,并不会被回收,没有超时限制和任务队列的限制,会创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。实现代码如下:

public static ExecutorService newFixedThreadPool(int mThreads){      

return new ThreadPoolExecutor(mThreads,mThreads,0L,TimeUtil.MILLISECONDS,new                         LinkedBlockingQueue());

}

        (2)newCachedThreadPool

          该模式下线程数量不定的线程池,只有非核心线程,最大值为Integer.MAX_VALUE,会创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。实现代码如下:

public static ExecutorService newCachedThreadPool(){

      return new ThreadPoolExecutor(0,Integer.MAX_VALUE,60L,TimeUtil.SECONDS,new                       SynchronousQueue());

}

        (3)newScheduledThreadPool

         该模式下核心线程是固定的,非核心线程没有限制,非核心线程闲置时会被回收。会创建一个定长线程池,执行定时任务和固定周期的任务。实现代码如下:

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){

            return new SchduledThreadPoolExecutor(corePoolSize)

}

public SchduledThreadPoolExecutor(int corePoolSize){

       super(corePoolSize,Integer.MAX_VALUE,0,NANOSECONDS,new DelayedWorkQueue());

}

        (4)newSingleThreadExecutor

        该模式下线程池内部只有一个线程,所有的任务都在一个线程中执行,会创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。实现代码如下:

public static ExecutorService newSingleThreadExecutor(){

          return new FinalizableDelegatedExecutorService(newThreadPoolExecutor(1,1,

                      0L,TimeUtil.MILLISECONDS,new LinkedBlockingQueue()));

}

使用案例程序如下:

Runnable runnable = new Runnable(){

          public void run(){

                    SystemClock.sleep(2000);

           }

}

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);

fixedThreadPool.execute(runnable);

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

cachedThreadPool.execute(runnable);

ScheduledExecutorService scheduledThereadPool = Executors.newScheduledThreadPool(4);

scheduledThereadPool.schedule()runnable,2000,TimeUtil.MAX_VALUE);//2000ms后执行。

//延迟10ms后,每隔1000ms执行一次

scheduledThereadPool.scheduleAtFixedRate(runnable,10,1000,TimeUtil.MILLISECONDS);

ExecutorService  singleThreadExecutor = Executors.newSingleThreadExecutor();

singleThreadExecutor.execute(runnable);


 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值