使用ListenableFuture
使用一种可监听的future 测试demo
public class TestListenableFuture {
public static void main(String[] args) {
ExecutorService delegate = Executors.newSingleThreadExecutor();
ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(delegate);
Callable callable = new Callable<String>() {
@Override
public String call() throws Exception {
int i = 0;
while (true){
Thread.currentThread().sleep(3000);
i++;
System.out.println("test call ,count =" + i);
if (i == 5){
System.out.println(1/0);
return "liyan";
}
}
}
};
ListenableFuture submit = listeningExecutorService.submit(callable);
/**
添加监听线程, 在任务成功或失败时候做出反应
*/
Futures.addCallback(submit, new FutureCallback<String>() {
@Override
public void onSuccess(@Nullable String result) {
System.out.println(" ok ,success");
}
@Override
public void onFailure(Throwable t) {
System.out.println("not ok ,exeception " + t.getMessage() );
}
},listeningExecutorService);
int i = 0;
while (true){
try {
Thread.currentThread().sleep(3000);
i++;
System.out.println("main thread ,count =" + i);
}catch (Exception e){
}
}
}
}