CallableとRunnableの違い



Difference Between Callable



からの転送: http://blog.sina.com.cn/s/blog_4c2e288b01000ark.html

呼び出し可能インターフェースはRunnableに似ています、どちらも、インスタンスが別のスレッドによって実行される可能性のあるクラス用に設計されています。ただし、Runnableは結果を返さず、チェックされた例外をスローすることはできません。



次の例を使用して、それらが互いにどのように異なるかを説明します。クラスの構築: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) { this.id = id } public String call() throws Exception { return 'result of TaskWithResult ' + id } }