Difference Between Callable



次の例を使用して、それらが互いにどのように異なるかを説明します。クラスの構築:public class RunnableClassimplements Runnable {public void run(){}} public class CallableClassimplements Callable {public V call()throws Exception {returnV}}クラス呼び出し:スレッドrunnable = new Thread(RunnableClass)runnable.start()Callable callable = new callableClass()FutureTask future = new FutureTask(int [])(callable)スレッドt = new Thread(future)t.start()if(future .isDone()){int [] intValue = future.get()}コードの説明:FutureTaskは、Callableオブジェクトの起動を担当し、Callableの戻り情報を取得するために使用できるプロキシクラスに属しています。


import java.util.concurrent.Callable import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** * Runnable is a separate task that performs work, but it does not return any value. * If you want the task to return a value when it is finished, you can implement the Callable interface. */ public class PrimeThread { public static void main(String[] args) throws Exception { ExecutorService service = Executors.newCachedThreadPool() System.out.println('==' + service.submit(new TaskResult(66)).get().toString()) } } class TaskResult implements Callable { private int id public TaskResult(int id) { = id } public String call() throws Exception { return 'result of TaskWithResult ' + id } }