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()。