package cas;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class testCallable implements Callable<myEntry>{
private String name;
public testCallable(int name) {
this.name = "thread-" + name;
}
@Override
public myEntry call() throws Exception {
double res = Math.random()*1000;
Thread.sleep(2000);
return new myEntry(name, res);
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newCachedThreadPool();
/*List<Future<myEntry>> ls = new ArrayList<Future<myEntry>>();
for(int i=0;i<1000;i++){
ls.add(executorService.submit(new testCallable(i)));
}*/
for(int i=0;i<1000;i++){
cs.submit(new testCallable(i));
}
executorService.shutdown();到这里为止不可以在submit线程,但是已经执行的线程继续执行
//executorService.shutdownNow();这里会立即中断正在睡眠的线程并抛出中断异常,返回未执行完成的所有任务的list
/*for(Future<myEntry> f:ls){
System.out.println(f.get()); //这里按照list的添加顺序去获取线程的返回值,但是如果该线程尚未返回,则get方法会阻塞住,等该线程放回获取到值后继续
}*/
<pre name="code" class="java"> CompletionService<myEntry> cs = new ExecutorCompletionService<myEntry>(executorService);
Future<myEntry> f; do{ f = cs.take();//阻塞
//f = cs.poll();//非阻塞
System.out.println(f.get()); //CompletionService维护一个Future返回的 BlockingQueue,并且先执行完成的先返回先取出,如果 BlockingQueue中还有数
据则不会出现阻塞,当整个队列为空而还有线程未返回才出现阻塞。 }while(f!=null); }}class myEntry{ private String key; private double value; public myEntry(String key,double value) { this.key = key; this.value = value; } @Override public String toString() { return key + " value is : " + value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public double getValue() { return value; } public void setValue(double value) { this.value = value; }}
shutdown调用后,不可以再submit新的task,已经submit的将继续执行。
shutdownNow试图停止当前正执行的task,并返回尚未执行的task的list