【问题标题】:What is callable in Java?Java中什么是可调用的?
【发布时间】:2014-09-16 23:14:20
【问题描述】:

标题几乎概括了它。

我想知道 callable 的概念和思想。我已经阅读了question here 关于可调用和可运行之间的区别。但是没有人显示代码并详细说明什么是可调用对象。我不想知道它们之间的区别。我想知道,

  1. 什么是可调用对象?

  2. 何时使用它们以及如何使用它们。

  3. 当他们为 安卓。

【问题讨论】:

    标签: java android callable


    【解决方案1】:

    你可以查看这个example:

    在此示例中,可调用任务在一秒后返回执行任务的线程的名称。我们正在使用 Executor 框架并行执行 100 个任务,并使用 Future 来获取提交任务的结果。

    package com.journaldev.threads;
    
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class MyCallable implements Callable<String> {
    
        @Override
        public String call() throws Exception {
            Thread.sleep(1000);
            //return the thread name executing this callable task
            return Thread.currentThread().getName();
        }
    
        public static void main(String args[]){
            //Get ExecutorService from Executors utility class, thread pool size is 10
            ExecutorService executor = Executors.newFixedThreadPool(10);
            //create a list to hold the Future object associated with Callable
            List<Future<String>> list = new ArrayList<Future<String>>();
            //Create MyCallable instance
            Callable<String> callable = new MyCallable();
            for(int i=0; i< 100; i++){
                //submit Callable tasks to be executed by thread pool
                Future<String> future = executor.submit(callable);
                //add Future to the list, we can get return value using Future
                list.add(future);
            }
            for(Future<String> fut : list){
                try {
                    //print the return value of Future, notice the output delay in console
                    // because Future.get() waits for task to get completed
                    System.out.println(new Date()+ "::"+fut.get());
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
            //shut down the executor service now
            executor.shutdown();
        }
    
    }
    

    您也可以查看Using Callable to Return Results From Runnables

    【讨论】:

    • 当它们在 Android 上发挥作用时
    【解决方案2】:

    Callable 类似于 Runnable 但它返回一个结果并可能抛出异常。 当您希望异步任务返回结果时使用它们。

    异步计算的返回结果用Future表示。

    您可以查看这个使用FutureTask 实现的简单示例(它实现了RunnableFuture 和Future)

    public static void main(String[] args) {
    
        // providing an anonymous callable to FutureTask
        RunnableFuture<String> future = new FutureTask<String>(
                new Callable<String>() {
                    @Override
                    public String call() throws InterruptedException {
                        System.out.println("sleeping");
                        Thread.sleep(2000);
                        System.out.println("returning");
                        return "hello-world";
                    }
    
                });
    
        Thread t = new Thread(future);
        t.start();
    
        try {
            // the get Waits if necessary for the computation to complete
            System.out.println(future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    
    }
    

    【讨论】:

    • 在运行未来任务的同一线程中等待有什么意义?
    • get 调用等待直到结果可用或被中断、取消或发生某些计算异常。请注意,在调用 get 时(在 main 中),处理仍在发生/或已经完成(在线程“t”中)。
    • @Jimmy Lunceford,您可以与其他线程共享未来的 ref 并调用 get 到您那里,但这里的重点是演示它的作用。即使在这里,未来的任务也会在线程“t”而不是“main”中执行
    猜你喜欢
    • 2010-11-12
    • 2010-09-11
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多