本文参考:《Thinking in Java》
我们在上一篇中知道,可以使用thread的构造器中接收Runnable对象,然后调用start方法开启线程。但是java.util.concurrent包提供了执行器 Executor来管理Thread对象。
public class LiftOff implements Runnable{
protected int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff() {
}
public String status(){
return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "). ";
}
public void run() {
// TODO Auto-generated method stub
while(countDown-- > 0){
System.out.println(status());
Thread.yield();
}
}
}
Executor
它长这样:
public interface Executor {
void execute(Runnable command);
}
所以我们的第二种启动执行线程的方式就是利用执行器:
Executor.execute(Runnable).
Executor在执行的时候使用内部的线程池完成操作.
ExcutorService
(具有服务生命周期的Executor)一个执行器的生命周期有三个状态: 运行, 关闭, 终止。
创建以后出去运行状态,当调用
ExecutorService.shutdown()后处于关闭状态。即不再接受新的任务.但是当前线程还是会继续处理关闭之前提交的所有任务。
如果已经关闭,还要向执行器提交任务,就会:
java.util.concurrent.RejectedExecutionException:
当所有添加的任务都已经执行完毕,处于终止状态。
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i<5; i++)
exec.execute(new LiftOff());
exec.shutdown();
}
补充:介绍三种线程池:
newCachedThreadPool: 创建一个可缓存线程池,如果线程池长度超过处理需求,可灵活的回收空间线程,如果没有可以回收的线程,那么新建线程。
注:在任何线程池中,现有线程在可能的情况下,都会被自动复用。
newCashedThreadPool 在程序执行的过程中通常会擦混剪与所需数量相同的线程,然后在它回收旧线程时停止创建新线程。所以是一般最优选择。
newFixedThreadPool: 创建一个定长线程池,可控制线程的最大并发数,超出的线程会在队列中等待。
因为一次性预先执行代价高昂的线程分配,因而也可以限制线程的数量了。
newSingleThreadExecutor 创建一个单例化的线程池,它只会用唯一的工作线程来执行任务。多个任务会排队。
就像是线程数量为1 的newFixedThreadPool
排队,且任意时刻任何线程中都只有唯一的任务在运行。
#0(9).
#0(8).
#0(7).
#0(6).
#0(5).
#0(4).
#0(3).
#0(2).
#0(1).
#0(Liftoff!).
#1(9).
#1(8).
#1(7).
#1(6).
#1(5).
#1(4).
#1(3).
#1(2).
#1(1).
#1(Liftoff!).
#2(9).
#2(8).
#2(7).
#2(6).
#2(5).
#2(4).
#2(3).
#2(2).
#2(1).
#2(Liftoff!).
#3(9).
#3(8).
#3(7).
#3(6).
#3(5).
#3(4).
#3(3).
#3(2).
#3(1).
#3(Liftoff!).
#4(9).
#4(8).
#4(7).
#4(6).
#4(5).
#4(4).
#4(3).
#4(2).
#4(1).
#4(Liftoff!).
从任务中产生返回值:
如果希望在完成任务时能够返回一个值,那么可以实现Callable接口而不是Runnable接口。
public class TaskWithResult implements Callable<String>{
private int id;
public TaskWithResult(int id){
this.id = id;
}
public String call() throws Exception {
// TODO Auto-generated method stub
return "id="+id;
}
}
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> res = new ArrayList<Future<String>>();
for(int i=0; i<10; i++){
res.add(exec.submit(new TaskWithResult(i)));
}
for(Future<String> fs : res){
try{
System.out.println(fs.get());
}catch(InterruptedException e){
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
exec.shutdown();
}
}
}
}
id=0
id=1
id=2
id=3
id=4
id=5
id=6
id=7
id=8
id=9
Callable的类型参数是从call()方法返回的值,并且必须使用ExecutorService.submit()调用它。
submit会产生Future对象,它用Callabl返回结果的特定类型进行了参数化。
换句话说,本来对于返回值的任务,我们的执行是这样的:
ExecutorService.execute( Runnable );
现在对于有返回值的是这样的:
Future< ? > = ExecutorService.submit( Callable );
( ? 就是call() 方法的返回值类型)