FutureTask详解及典型用例----高并发实现烧水泡茶
Future接口:作用为获取Callable接口的返回值
FutureTask类为Future接口子类,该类独有的特点为在高并发情况下不论有多少个线程,均只执行一次任务。
get()方法的作用为阻塞当前线程直到有返回值为止。
使用Future接口中get()方法的两种情况:
(1)提交线程的同时调用get()方法
class CallableTest implements Callable<String>{
private static Integer ticket=10;
@Override
public String call() throws Exception {
while (ticket>0){
System.out.println(Thread.currentThread().getName()+"还剩"+ticket--+"张票");
}
return "票已经卖完啦";
}
}
public class ThreadTest{
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService service=Executors.newCachedThreadPool();
Callable<String> callable=new CallableTest();
for(int i=0;i<5;i++){
String str=service.submit(callable).get();
System.out.println(str);
}
service.shutdown()