java线程池(newFixedThreadPool)的使用


import java.util.concurrent.*;

import java.util.List;
import java.util.ArrayList;

/**
 * java线程池的使用 指定线程池大小,并发执行任务
 */
public class Test {
	@SuppressWarnings("rawtypes")
	public static void main(String[] args) throws ExecutionException, InterruptedException {
		long start = System.currentTimeMillis();
		System.out.println("---程序开始运行---当前时间:" + start);

		// 创建一个线程池能容纳2个线程
		int taskSize = 2;
		ExecutorService pool = Executors.newFixedThreadPool(taskSize);
		// 创建多个有返回值的任务,用List接收
		List<Future> list = new ArrayList<Future>();
		// String为返回值类型
		Callable<String> c1 = new Callable<String>() {
			@Override
			public String call() throws Exception {
				// 设定程序执行耗时2秒
				Thread.sleep(2000);
				return "任务用时2秒,当前任务时间:" + System.currentTimeMillis() + ",线程名:" + Thread.currentThread().getName();
			}
		};
		Callable<String> c2 = new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(1000);
				return "任务用时1秒,当前任务时间:" + System.currentTimeMillis() + ",线程名:" + Thread.currentThread().getName();
			}
		};
		Callable<String> c3 = new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(3000);
				return "任务用时3秒,当前任务时间:" + System.currentTimeMillis() + ",线程名:" + Thread.currentThread().getName();
			}
		};
		Callable<String> c4 = new Callable<String>() {
			@Override
			public String call() throws Exception {
				Thread.sleep(1000);
				return "任务用时1秒,当前任务时间:" + System.currentTimeMillis() + ",线程名:" + Thread.currentThread().getName();
			}
		};
		// 执行任务并获取Future对象
		Future f1 = pool.submit(c1);
		Future f2 = pool.submit(c2);
		Future f3 = pool.submit(c3);
		Future f4 = pool.submit(c4);
		list.add(f1);
		list.add(f2);
		list.add(f3);
		list.add(f4);
		// 关闭线程池
		pool.shutdown();

		// 遍历所有并发任务的运行结果
		for (Future f : list) {
			// 从Future对象上获取任务的返回值,并输出到控制台
			System.out.println(f.get());
		}

		long end = System.currentTimeMillis();
		System.out.println("---程序结束运行---当前时间:" + end + ",共耗时:" + (end - start) / 1000 + "秒");

	}
}

运行结果:

---程序开始运行---当前时间:1538207916806
任务用时2秒,当前任务时间:1538207918811,线程名:pool-1-thread-1
任务用时1秒,当前任务时间:1538207917811,线程名:pool-1-thread-2
任务用时3秒,当前任务时间:1538207920810,线程名:pool-1-thread-2
任务用时1秒,当前任务时间:1538207919810,线程名:pool-1-thread-1
---程序结束运行---当前时间:1538207920810,共耗时:4秒

newFixedThreadPool:创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值