我们知道使用callable可以获得线程中的返回值,下面我们简单介绍callable的使用。
1 创建两个callable的实现类
1.1 BumCallable
public class BumCallable implements Callable {
@Override
public Object call() throws Exception {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "包子出锅";
}
}
1.2 ColdDishCallable
public class ColdDishCallable implements Callable {
@Override
public Object call() throws Exception {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "凉菜出锅";
}
}
2 使用创建好的两个callable的实现类
public class ResultMain {
static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,10,1000, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(16));
public static void main(String[] args) throws ExecutionException, InterruptedException {
long start = System.currentTimeMillis();
Callable callable1 = new ColdDishCallable();
/*FutureTask<String> futureTask1 = new FutureTask<String>(callable1);
new Thread(futureTask1).start();*/
Future<String> future1 = threadPoolExecutor.submit(callable1);
Callable callable2 = new BumCallable();
/*FutureTask<String> futureTask2 = new FutureTask<String>(callable2);
new Thread(futureTask2).start();*/
Future<String> future2 = threadPoolExecutor.submit(callable2);
System.out.println(future1.get());
System.out.println(future2.get());
long end = System.currentTimeMillis();
System.out.println("执行时间:"+(end-start));
}
}