1) execute() 方法用于提交不需要返回值的任务,所以无法判断任务是否被线程池执行成功与否;
2) submit()方法用于提交需要返回值的任务。线程池会返回一个future类型的对象,通过这个future对象可以判断任务是否执行成功,并且可以通过future的get()方法来获取返回值,get()方法会阻塞当前线程直到任务完成,而使用get(long timeout,TimeUnit unit) 方法则会阻塞当前线程一段时间后立即返回,这时候有可能任务没有执行完。
public class callThread implements Callable {
int key;
public callThread(int key) {
this.key = key;
}
@Override
public Integer call() throws Exception {
return key ;
}
}
public class ThreadCount {
static volatile int a=1;
public static void main(String[] args) throws ExecutionException, InterruptedException {
CountDownLatch countDownLatch=new CountDownLatch(a);
ExecutorService threadPool = Executors.newCachedThreadPool();
int o1,o2;
{
o1 = (int) threadPool.submit(new callThread(20)).get();
o2 = (int) threadPool.submit(new callThread(25)).get();
countDownLatch.countDown();
}
countDownLatch.await();
System.out.println(o1+o2);
}
}