这个标题非常概括。
我想知道可调用的概念和想法。我读过一个关于可调用和可运行之间的区别的问题。但是没有人显示代码并给出可调用的细节。我不想知道他们之间的区别。我想知道,
什么是可调用的?
何时使用它们以及如何使用它们。
当他们为安卓。
You can check this实例:P></
在本工作callable example the name of the归来后的一个线程执行第二任务。我们是用to execute 100 executor框架平行和今后任务使用to get the result of the提交任务。P></
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 {
@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> list = new ArrayList>();
//Create MyCallable instance
Callable callable = new MyCallable();
for(int i=0; i< 100; i++){
//submit Callable tasks to be executed by thread pool
Future future = executor.submit(callable);
//add Future to the list, we can get return value using Future
list.add(future);
}
for(Future 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 to check返回结果从runnablesP></
回答得很好!
当他们对Android采取行动时
callable is similar to a result返回运行,但它可以把数据库和安。当你期望你用them to Return Result异步任务。P></
computation is the result of Asynchronous returned by公社的未来。P></
You can check this simple example要实现(implements runnablefuture which using futuretask和未来)P></
public static void main(String[] args) {
// providing an anonymous callable to FutureTask
RunnableFuture future = new FutureTask(
new Callable() {
@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时(在主线程中),处理仍在进行/或已经完成(在线程"t")。
@吉米。伦斯福德,你可以和其他人分享未来的裁判,然后打电话到你那里,但这里的重点是演示它的作用。即使在这里,未来的任务也在线程"t"而不是"main"中执行。