import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestOften{
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i<5;i++)
exec.execute(new ListOff());
exec.shutdown();
}
}
class ListOff implements Runnable{
protected int countDown = 10;
public static int taskCount = 0;//全局的
private final int id = taskCount++;//私有的,属于每个对象,只修改一次
public ListOff(){
}
public String status(){
return id+" "+(countDown > 0?countDown:"listOff");
}
public void run(){
while(countDown-->0){
System.out.println(status());
Thread.yield();
}
}
}
Executors类可以获得ExecutorServices对象,ExecutorServices接口继承了Executor,ExecutorServices里面提供了对线程的操作方法
同理,Executors.newFixedThreadPool(int nThreads) 创建固定线程数的线程池, 返回一个Executor;
newSingleThreadExecutor() :,返回一个Executor, 按序列化执行任务,就是按提交任务的顺序执行任务