package concurrentThread;
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 CallableAndFuture {
public static void main(String[] args) throws InterruptedException,
ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(10);
CompletionService<Boolean> exchangeResult = new ExecutorCompletionService<Boolean>(
pool);
for (int i = 1; i <= 10; i++) {
exchangeResult.submit(new TaskWorker(i)) ; //这里会报错,请问为什么呢?
}
for (int i = 0; i < 10; i++) {
System.out.println(exchangeResult.take().get());
}
try {
for (int j = 0; j < 10; j++) {
Future<Boolean> future = exchangeResult.take();
if (future.get() == true)
System.out.println(" exchange thread " + j + " succeed!");
else
System.out.println(" exchange thread " + j + " fail!");
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
pool.shutdown() ;
}
private class TaskWorker implements Callable<Boolean> {
int i = 0;
public TaskWorker(Integer i) {
this.i = i;
}
@Override
public Boolean call() throws Exception {
System.out.println(Thread.currentThread().getName() + " get " + i);
return true;
}
}
}
|
|