Guava对Future的支持(回调)

阅读更多

//1.使用Callable返回执行结果(获取返回值get()是阻塞方法)
public class FutureTest {
public static void main(String[] args) throws Exception{
FutureTask future = new FutureTask(new CallableTask("hi"));
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(future);
System.out.println("提交任务 "+new Date());

Thread.sleep(1000);
System.out.println("任务执行结果:" + future.get() + new Date()); //get()阻塞
System.out.println("game over!");
executor.shutdown();
}
}

class CallableTask implements Callable{
private String para;
public String call() throws Exception {
StringBuffer sb = new StringBuffer();
for(int i=0;i<10;i++) {
sb.append(para);
Thread.sleep(300);
}
return sb.toString();
}
public CallableTask(String para) {
this.para=para;
}
}

2.Guava对Future的支持(增加listener):Future的执行并没有阻塞主线程
public class GuavaFutureTest {

public static void main(String[] args) {
ExecutorService exe = Executors.newFixedThreadPool(5);
ListeningExecutorService service = MoreExecutors.listeningDecorator(exe);
final ListenableFuture task = service.submit(new CallableTask("how"));

Runnable result = new Runnable() {
public void run() {
System.out.println("异步处理成功");
try {
System.out.println(task.get());
} catch (Exception e) {
e.printStackTrace();
}
}
};
//增加监听器
task.addListener(result, MoreExecutors.directExecutor());
System.out.println("game over");
}
}

(2)增加对异常的处理
public class GuavaFutureTest2 {

public static void main(String[] args) {
ExecutorService exe = Executors.newFixedThreadPool(5);
ListeningExecutorService service = MoreExecutors.listeningDecorator(exe);
ListenableFuture task = service.submit(new CallableTask("how"));
FutureCallback callback = new FutureCallback() {
public void onFailure(Throwable e) {
System.out.println("异步处理失败:"+e.getMessage());
}
public void onSuccess(String s) {
System.out.println("异步处理成功");
}
};
Futures.addCallback(task, callback, MoreExecutors.newDirectExecutorService());
System.out.println("game over");
}
}


你可能感兴趣的:(多线程)