java concurrent Callable

实现Callable接口的类其实就是一个任务,可以异步执行并返回结果。

通过ExecutorService.submit 方法提交一个callable任务,并且通过Future对象来获得结果。

Future对象可以取消运行任务,设置等待时间,获取任务状态,最终获得任务结果。

 1 public static void main(String[] args) {
2 ExecutorService exec = Executors.newCachedThreadPool();
3
4 Future<String> future = exec.submit(new CallableThread(0));
5
6 try {
7 System.out.println("Got it: " + future.get(1000, TimeUnit.SECONDS));
8 } catch (InterruptedException e) {
9 e.printStackTrace();
10 } catch (ExecutionException e) {
11 e.printStackTrace();
12 } catch (TimeoutException e) {
13 e.printStackTrace();
14 }finally{
15 exec.shutdown();
16 }
17 }
 1 public class CallableThread implements Callable<String> {
2
3 private int count = 0;
4
5 public CallableThread(int count){
6 this.count = count;
7 }
8
9 public String call() throws Exception {
10 doSomething();
11 return "Thread Name: " + Thread.currentThread().getName() + " , count: " + count;
12 }
13
14 private void doSomething(){
15 while(count < 5){
16 count++;
17 System.out.println("Thread Name: " + Thread.currentThread().getName() + " , count: " + count);
18 try {
19 Thread.sleep(1000);
20 } catch (InterruptedException e) {
21 e.printStackTrace();
22 }
23 }
24 }
25
26 }



转载于:https://www.cnblogs.com/lostyue/archive/2012/03/22/2411982.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的Callable是一个接口,它可以让我们在执行某个任务时返回一个结果,并且可以抛出异常。与Runnable接口不同的是,Callable接口中的call()方法可以返回值,并且可以抛出异常,而Runnable接口中的run()方法没有返回值,也不能抛出异常。 在使用Callable时,我们需要借助ExecutorService来执行任务。ExecutorService是一个Java线程池框架,它可以管理线程池的创建、销毁和复用。我们可以通过调用ExecutorService的submit()方法来提交Callable任务,submit()方法会返回一个Future对象,我们可以通过Future对象来获取任务的执行结果或者取消任务的执行。 下面是一个使用Callable和ExecutorService的示例代码: ``` import java.util.concurrent.*; public class CallableExample { public static void main(String[] args) { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Integer> task = () -> { try { TimeUnit.SECONDS.sleep(1); return 123; } catch (InterruptedException e) { throw new IllegalStateException("task interrupted", e); } }; Future<Integer> future = executor.submit(task); System.out.println("future done? " + future.isDone()); Integer result = null; try { result = future.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } System.out.println("future done? " + future.isDone()); System.out.println("result: " + result); executor.shutdown(); } } ``` 在上面的代码中,我们创建了一个Callable任务task,它会在执行后返回整数123。我们通过ExecutorService的submit()方法来提交任务,并且通过Future对象来获取任务的执行结果。由于任务执行需要一定的时间,我们在获取结果之前先通过future.isDone()方法检查任务是否已经完成。最后,我们关闭了ExecutorService线程池。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值