JAVA多线程实现-可控最大并发数线程池(newFixedThreadPool)

上篇文章中介绍了单线程化线程池newSingleThreadExecutor,可控最大并发数线程池(newFixedThreadPool)与其最大的区别是可以通知执行多个线程,可以简单的将newSingleThreadExecutor理解为newFixedThreadPool(1)。例如运行一下两个程序:

单线程化线程池(newSingleThreadExecutor)示例:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolByNewSingleThreadExecutor {

	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() {
				@Override
				public void run() {
					Thread.currentThread().setName("Thread i = " + index);
					System.out.println(Thread.currentThread().getName() + " index = " + index);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						System.out.println("exception");
					}
				}
			});
		}
		singleThreadExecutor.shutdown();
		System.out.println("on the main thread...");
		
	}

}

可控最大并发数线程池(newFixedThreadPool)示例:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolByNewFixedThreadPool {
	public static void main(String[] args) {
		
		ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 10; i++) {
			final int index = i;
			newFixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					Thread.currentThread().setName("Thread i = " + index);
					System.out.println(Thread.currentThread().getName() + " index = " + index);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						System.out.println("exception");
					}
				}
			});
		}
		newFixedThreadPool.shutdown();
		System.out.println("on the main thread...");
	}

}


结果从显示上看虽然很相似,但是观察到的执行效果确实完全不一致的,newSingleThreadPool中,只有一个线程,每次输出一行后暂停0.5秒,newFixedThreadPool(3)中可以创建3个线程,一次输出3行后暂停0.5秒(当然是这三个线程都暂停0.5秒)。

动画对比如下所示:

单线程化线程池

可控最大并发数线程池

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值