多线程篇六:线程池
Posted 陈小兵
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程篇六:线程池相关的知识,希望对你有一定的参考价值。
1.固定大小的线程池
ExecutorService threadPools1=Executors.newFixedThreadPool(3);
for(int i=1;i<=10;i++){ final int task=i; //循环10次,一共往线程池里面放10个任务 threadPools1.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" loop of "+task); } }); } System.out.println("The task is executd completed....."); // 1.使用固定线程池threadPools1: // 输出结果: 10任务每次同时有3个线程进行处理,每个线程处理一个。直到处理完10个任务 The task is executd completed..... pool-1-thread-2 loop of 2 pool-1-thread-1 loop of 1 pool-1-thread-3 loop of 3 pool-1-thread-1 loop of 4 pool-1-thread-2 loop of 5 pool-1-thread-3 loop of 6 pool-1-thread-1 loop of 7 pool-1-thread-3 loop of 9 pool-1-thread-2 loop of 8 pool-1-thread-1 loop of 10
2.缓存线程池(池内没有固定的线程数,根据任务的多少而创建多少个线程)
ExecutorService threadPools2=Executors.newCachedThreadPool();
for(int i=1;i<=10;i++){ final int task=i; //循环10次,一共往线程池里面放10个任务 threadPools2.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" loop of "+task); } }); } System.out.println("The task is executd completed....."); /* * 2.使用缓存线程池threadPools2: * 输出结果:(线程池内直接创建10个线程,分别处理10个任务 ) The task is executd completed..... pool-2-thread-10 loop of 10 pool-2-thread-9 loop of 9 pool-2-thread-8 loop of 8 pool-2-thread-7 loop of 7 pool-2-thread-6 loop of 6 pool-2-thread-5 loop of 5 pool-2-thread-4 loop of 4 pool-2-thread-3 loop of 3 pool-2-thread-1 loop of 1 pool-2-thread-2 loop of 2 */
3.单线程的线程池(池内固定有一个线程,当前线程死后会自动再创建一个,始终维持1一个线程)--比如实现案例:如何实现线程死后重新启动
ExecutorService threadPools3=Executors.newSingleThreadExecutor();
for(int i=1;i<=10;i++){ final int task=i; //循环10次,一共往线程池里面放10个任务 threadPools3.execute(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+" loop of "+task); } }); } System.out.println("The task is executd completed....."); /* * 3.使用单一线程池 threadPools3 * 输出结果:(由单一线程逐一处理10个任务 ) The task is executd completed..... pool-3-thread-1 loop of 1 pool-3-thread-1 loop of 2 pool-3-thread-1 loop of 3 pool-3-thread-1 loop of 4 pool-3-thread-1 loop of 5 pool-3-thread-1 loop of 6 pool-3-thread-1 loop of 7 pool-3-thread-1 loop of 8 pool-3-thread-1 loop of 9 pool-3-thread-1 loop of 10 */
4.关闭线程池
//等池内的任务执行完,销毁掉线程池. threadPools3.shutdown(); //立即销毁掉线程池.不会等待任务是否完成 threadPools3.shutdownNow();
5.调度线程池(定时器的线程池)
ScheduledExecutorService scheduleThreadPools=Executors.newScheduledThreadPool(3); //10s之后执行 scheduleThreadPools.schedule(new Runnable() { @Override public void run() { System.out.println("bombing!"); } }, 10, TimeUnit.SECONDS); //固定频率的执行 10s之后执行,每个2S执行一次 scheduleThreadPools.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("bombing!"); } }, 10, 2,TimeUnit.SECONDS);
以上是关于多线程篇六:线程池的主要内容,如果未能解决你的问题,请参考以下文章
newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段