标题几乎概括了它。
我想知道callable的概念和思想。我在这里读到一个关于可调用和可运行之间差异的问题。但没有人展示代码并详细说明callable是什么。我不想知道它们之间的区别。我想知道,
-
何时使用,如何使用。
-
当他们开始行动Android .
你可以检查这个例子:
在这个例子中,Callable task在一秒钟后返回执行该任务的线程的名称。我们使用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();
}
}
你也可以检查使用Callable从Runnables返回结果
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();
}
}