package com.ctyun.thread.concurrent; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @Description TODO * @author zhanghw * @since 2015年12月12日 * @version V1.0 */ public class ThreadPoolDemo { public static void main(String[] args) { /** * 创建一个固定大小的线程池 */ // ExecutorService threadPool = Executors.newFixedThreadPool(3); /** * 创建一个缓存线程池,线程池大小会随着线程任务的多少儿变化。(会自动回收已执行完毕的线程) */ // ExecutorService threadPool = Executors.newCachedThreadPool(); /** * 创建一个只有一个线程的线程池 */ ExecutorService threadPool = Executors.newSingleThreadExecutor(); for (int i = 0; i < 10; i++) { final int taskLoop = i; threadPool.execute(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " ,the loop is:" + i + ",the task is" + taskLoop); } } }); } System.out.println("all task has commited!"); /** * 在线程执行完毕之后,程序不会结束,因为线程池中还有三个线程 可以调用threadPool.shutdown()方法,对已经执行完毕的线程进行清理(即杀死所有的线程),并结束任务 */ // threadPool.shutdown();//当所有线程都执行完毕时,清除线程 // threadPool.shutdownNow();//不管线程池中线程中任务是否结束,都清除线程池中所有线程 /** * 创建一个定时任务调度的线程池 */ ScheduledExecutorService threadPool2 = Executors.newScheduledThreadPool(3); threadPool2.schedule(new Runnable() { @Override public void run() { System.out.println("boning"); } }, 1L, TimeUnit.SECONDS); } }
线程池的类型分类:
原文:http://www.cnblogs.com/zhangshiwen/p/5042314.html