Callable实现

1.接口的定义:

public interface Callable<V>   
{   
    V call() throws Exception;   
} 
  • 1
  • 2
  • 3
  • 4

2.Callable和Runnable的异同

先看下Runnable接口的定义

public interface Runnable {
    public abstract void run();
}
  • 1
  • 2
  • 3

Callable的call()方法类似于Runnable接口中run()方法,都定义任务要完成的工作,实现这两个接口时要分别重写这两个方法,主要的不同之处是call()方法是有返回值的(其实还有一些区别,例如call方法可以抛出异常,run方法不可以),运行Callable任务可以拿到一个Future对象,表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。

3. Callable类型的任务可以有两种执行方式:

我们先定义一个Callable任务MyCallableTask:

class MyCallableTask implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("线程在进行计算");
        Thread.sleep(3000);
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

①借助FutureTask执行 
FutureTask类同时实现了两个接口,Future和Runnable接口,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

借助FutureTask执行的大体流程是:

Callable<Integer> mycallabletask = new MyCallableTask();  
FutureTask<Integer> futuretask= new FutureTask<Integer>(mycallabletask);  
new Thread(futuretask).start();
  • 1
  • 2
  • 3

通过futuretask可以得到MyCallableTask的call()的运行结果: 
futuretask.get(); 
②借助线程池来运行 
线程池中执行Callable任务的原型例如:

public interface ExecutorService extends Executor {

  //提交一个Callable任务,返回值为一个Future类型
  <T> Future<T> submit(Callable<T> task);

  //other methods...
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

借助线程池来运行Callable任务的一般流程为:

  ExecutorService exec = Executors.newCachedThreadPool();
  Future<Integer> future = exec.submit(new MyCallableTask());
  • 1
  • 2

通过future可以得到MyCallableTask的call()的运行结果: 
future.get(); 
在网上看到了几个比较好的代码例子: 
a.Callable任务借助FutureTask运行:

public class CallableAndFutureTask {
    public static void main(String[] args) {
        Callable<Integer> callable = new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        };
        FutureTask<Integer> future = new FutureTask<Integer>(callable);
        new Thread(future).start();
        try {
            Thread.sleep(5000);
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

b.Callable任务和线程池一起使用,然后返回值是Future:

public class CallableAndFuture {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<Integer> future = threadPool.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt(100);
            }
        });
        try {
            Thread.sleep(5000);// 可能做一些事情
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

以上a,b例子摘自(http://blog.csdn.net/ghsau/article/details/7451464
c.当执行多个Callable任务,有多个返回值时,我们可以创建一个Future的集合,例如:

class MyCallableTask implements Callable<String> {
    private int id;  
    public OneTask(int id){  
        this.id = id;  
    }  
    @Override  
    public String call() throws Exception {  
        for(int i = 0;i<5;i++){
            System.out.println("Thread"+ id);  
            Thread.sleep(1000); 
        }  
        return "Result of callable: "+id;  
    }   
}
public class Test {   

    public static void main(String[] args) {  
        //Callable<String> mycallabletask = new MyCallableTask(1);  
        ExecutorService exec = Executors.newCachedThreadPool();    
        ArrayList<Future<String>> results = new ArrayList<Future<String>>();      

        for (int i = 0; i < 5; i++) {    
            results.add(exec.submit(new MyCallableTask(i)));    
        }    

        for (Future<String> fs : results) {    
            if (fs.isDone()) {    
                try {  
                    System.out.println(fs.get());   
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            } else {    
                System.out.println("MyCallableTask任务未完成!");    
            }    
        }    
        exec.shutdown();  
    }  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

那么引入Callable接口具有哪些好处呢? 
①可以获得任务执行返回值; 

②通过与Future的结合,可以实现利用Future来跟踪异步计算的结果。


转载自:https://blog.csdn.net/sunp823/article/details/51569314

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java 中,可以通过实现 Callable 接口,实现多线程操作。Callable 接口与 Runnable 接口类似,都是用来实现多线程操作的接口。但是,Callable 接口支持返回结果和抛出异常。 下面是一个简单的示例,演示如何使用 Callable 实现多线程操作: ``` import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MyCallable implements Callable<String> { private String name; public MyCallable(String name) { this.name = name; } @Override public String call() throws Exception { System.out.println("Thread " + name + " is running..."); Thread.sleep(5000); return "Hello from thread " + name; } public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(3); Future<String> result1 = executorService.submit(new MyCallable("Thread-1")); Future<String> result2 = executorService.submit(new MyCallable("Thread-2")); Future<String> result3 = executorService.submit(new MyCallable("Thread-3")); System.out.println(result1.get()); System.out.println(result2.get()); System.out.println(result3.get()); executorService.shutdown(); } } ``` 在上面的示例中,我们创建了一个实现Callable 接口的类 MyCallable。在 call() 方法中,我们输出了当前线程的名称,然后让线程休眠 5 秒,最后返回一个字符串。 在 main() 方法中,我们创建了一个 ExecutorService,并向其提交了三个 MyCallable 对象。ExecutorService.submit() 方法会返回一个 Future 对象,可以使用 get() 方法获取 MyCallable 对象的返回值。最后,我们关闭了 ExecutorService。 执行上面的代码,可以看到如下输出: ``` Thread Thread-1 is running... Thread Thread-2 is running... Thread Thread-3 is running... Hello from thread Thread-1 Hello from thread Thread-2 Hello from thread Thread-3 ``` 从输出结果可以看出,我们创建的三个线程都在运行,而且每个线程都在休眠 5 秒钟。而且,我们使用 Future 对象获取了每个线程的返回值。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值