在Java 5之后,并发编程引入了一堆新的启动、调度和管理线程的API。Executor框架便是Java 5中引入的,其内部使用了线程池机制,它在java.util.cocurrent 包下,通过该框架来控制线程的启动、执行和关闭,可以简化并发编程的操作。因此,在Java 5之后,通过Executor来启动线程比使用Thread的start方法更好,更易管理,效率更好(用线程池实现,节约开销)。
Executor主要由三大部分组成:
1、任务:Runnable接口或者Callable接口实现;
2、执行:核心接口Executor、子接口ExecutorSerivce及其实现类ThreadPoolExecutor;
3、结果:Future接口及其实现类FutureTask。
public static class ThreadOne implements Runnable {
@Override
public void run() {
System.out.println("I'm " + Thread.currentThread().getName());
}
}
@Test
public void testRunTask() {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; i++) {
// 执行Runnable任务,无返回值
executorService.execute(new ThreadOne());
System.out.println(i + 11);
}
executorService.shutdown();
}
public static class ThreadTwo implements Callable<String> {
private int id;
public ThreadTwo(int id) {
this.id = id;
}
@Override
public String call() throws Exception {
String name = Thread.currentThread().getName();
System.out.println(name + " is called");
return name + " result is " + id;
}
}
@Test
public void testCallTask() throws InterruptedException, ExecutionException {
List<Future<String>> list = new ArrayList<>();
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 20; i++) {
// 执行Callable任务,并将结果保存在future中
Future<String> future = executorService.submit(new ThreadTwo(i + 1));
list.add(future);
}
for (Future<String> future : list) {
// Future返回如果没有完成,则一直循环等待,直到Future返回完成
while (!future.isDone()) {
}
// 输出各个线程(任务)执行的结果
System.out.println(future.get());
}
// 启动一次顺序关闭,执行以前提交的任务,不接受新任务
executorService.shutdown();
}
public static class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 正在执行。。。");
}
}
@Test
public void testSelfThreadPool() {
// 创建等待队列
BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20);
// 创建线程池,池中保存的线程数为3,允许的最大线程数为5
ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5, 50, TimeUnit.MILLISECONDS, bqueue);
// 创建七个任务
Runnable t1 = new MyThread();
Runnable t2 = new MyThread();
Runnable t3 = new MyThread();
Runnable t4 = new MyThread();
Runnable t5 = new MyThread();
Runnable t6 = new MyThread();
Runnable t7 = new MyThread();
// 每个任务会在一个线程上执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);
pool.execute(t7);
// 关闭线程池
pool.shutdown();
}