import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.RateLimiter;
/**
* @author Andypan
* @ListenableFutureTest.java
* @{describe}
* @date 2017年7月28日 下午4:42:21
*/
public class ListenableFutureTest
{
public static void main(String[] args) throws Exception
{
testListenableFuture();
}
public static void testListenableFuture() throws Exception
{
// 通过装饰器模式获取服务
ListeningExecutorService les = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
// 此处还可以处理并发访问的线程数
// 每秒不超过5个任务被提交
RateLimiter rl = RateLimiter.create(5);
// 超过线程数会被堵塞
rl.acquire();
ListenableFuture<String> lf = les.submit(new Callable<String>() {
@Override
public String call() throws Exception
{
TimeUnit.SECONDS.sleep(5);
return "test";
}
});
// 同步获取结果
System.out.println(lf.get());
Futures.addCallback(lf, new FutureCallback<String>() {
@Override
public void onSuccess(String result)
{
System.out.println(result);
}
@Override
public void onFailure(Throwable t)
{
System.out.println(222);
}
});
}
}