2-JDK自带4种线程池

Java建议使用Executors方式使用线程池,Executors最终使用的是ThreadPoolExecutor来实现各种线程池的,所以,如果你足够熟练,请直接使用ThreadPoolExecutor来定制属于你自己的线程池吧。下面我们先来说说JDK自带的4中线程池吧,先来个总览

 

使用方式:

Executors.newCachedThreadPool();
Executors.newFixedThreadPool(3);
Executors.newScheduledThreadPool(3);
Executors.newSingleThreadExecutor();

1 Executors.newCachedThreadPool()
创建一个可缓存线程的线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
2 Executors.newFixedThreadPool()
创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
3 Executors.newScheduledThreadPool()
创建一个定长线程池,支持定时及周期性任务执行。
4 Executors.newSingleThreadExecutor()
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

构造函数

通过构造函数我们可以看到线程池内部都是使用ThreadPoolExecutor来创建线程池。

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue());
}

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

使用方式

创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。示例代码如下:
线程池中线程无限大,没有任务队列,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。这个线程池可能会创建很多线程,使用时要谨慎。

cachedThreadPool

public class TestMain {
	public static void main(String[] args) {
		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

		for (int i = 0; i < 10; i++) {
			final int index = i;
			try {
				Thread.sleep(index * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			cachedThreadPool.execute(new Runnable() {
				public void run() {
					System.out.println(index);
				}
			});
		}
	}
}

fixedThreadPool

创建一个定长线程池,核心线程数和最大线程数相等,使用LinkedBlockingQueue作为任务队列。可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:
因为线程池大小为3,每个任务输出index后sleep 2秒,所以每两秒打印3个数字。
定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()

public class TestMain {
	public static void main(String[] args) {
		ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 10; i++) {
			final int index = i;
			fixedThreadPool.execute(new Runnable() {
				public void run() {
					try {
						System.out.println(index);
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
	}
}

scheduledThreadPool

核心线程数自行指定,最大线程数为无限,使用DelayedWorkQueue作为任务队列。支持定时及周期性任务执行。延迟执行示例代码如下:
表示延迟3秒执行。

public class TestMain {
	public static void main(String[] args) {
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
		scheduledThreadPool.schedule(new Runnable() {
			public void run() {
				System.out.println("delay 3 seconds");
			}
		}, 3, TimeUnit.SECONDS);
	}
}

定期执行示例代码如下:表示延迟1秒后每3秒执行一次。

public class TestMain {
	public static void main(String[] args) {
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
		scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
			public void run() {
				System.out.println("delay 1 seconds, and excute every 3 seconds");
			}
		}, 1, 3, TimeUnit.SECONDS);
	}
}

singleThreadExecutor

创建一个单线程化的线程池,核心线程数和最大线程数等于1,使用LinkedBlockingQueue作为任务队列。它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。示例代码如下:结果依次输出,相当于顺序执行各个任务

public class TestMain {
	public static void main(String[] args) {
		ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
		for (int i = 0; i < 10; i++) {
			final int index = i;
			singleThreadExecutor.execute(new Runnable() {
				public void run() {
					try {
						System.out.println(index);
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值