java 获取线程某个_JAVA获取线程执行结果的几种方式

获取线程执行结果的几种方式

1、Callable 线程

public class FetchAdTask implements Callable {

[@Override](https://my.oschina.net/u/1162528)

public Ad call() throws Exception {

System.out.println("fetch task");

sleep(1000L);

return null;

}

}

2、使用Future,包括 FutureTask、CompletableFuture

CompletableFuture.get();

Future 的优点:可以对任务设置时限,如果超时了,可以取消,然后返回一个默认结果,防止 某一个任务出现问题,导致系统出现问题。

f.get(timeLeft, TimeUnit.NANOSECONDS);

或者通过 invokeAll() 返回限定时间范围内的所有任务的结果。

executor.invokeAll(tasks, time, unit);

CompletableFuture, 使用 supplyAsync 方法提交线程,使用 get 方法获取结果。

CompletableFuture task3 = CompletableFuture.supplyAsync(() -> {

System.out.println("任务3, 线程名字" + Thread.currentThread().getName());

try {

sleep(3000);

} catch (InterruptedException e) {

e.printStackTrace();

}

return 3;

});

CompletableFuture.allOf(task1, task2, task3, task4);

System.out.println("end: " + new Date());

task1.get();

3、使用 CompletionService,

CompletionService.take();

例子

private static final long TIME_BUDGET = 100L;

private static final Ad DEFAULT_AD = new Ad();

private final ExecutorService executor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1,

Runtime.getRuntime().availableProcessors() + 1, 0L,

TimeUnit.MILLISECONDS, new LinkedBlockingQueue(1000));

public static void main(String[] args) {

try {

Test616LimitedTimeTask task = new Test616LimitedTimeTask();

task.test();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

/**

* 测试超时取消

*

* [@throws](https://my.oschina.net/throws) InterruptedException

*/

void test() throws InterruptedException {

Ad ad = null;

long endNanos = System.nanoTime() + TIME_BUDGET;

Future f = executor.submit(new FetchAdTask());

try {

long timeLeft = endNanos - System.nanoTime();

// 增加参数 超时时间和超时时间的单位

ad = f.get(timeLeft, TimeUnit.NANOSECONDS);

} catch (ExecutionException e) {

ad = DEFAULT_AD;

} catch (TimeoutException e) {

// 超时,取消任务

ad = DEFAULT_AD;

System.out.println("超时取消");

f.cancel(true);

}

}

优点:多个 CompletionService 可以共享一个 Executor,因此可以创建一个对于特定计算私有, 又能共享一个公共 Executor 的 ExecutorCompletionService。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值