java callable和Future

最近看同事的代碼,他們在一個項目中用到了java的excutor框架,我也參考了《java併發編程實踐》這本書,將相應的知識點看了看。callable和Future的一些內容總結如下:

Callable與 Future 兩功能是Java 5版本中加入的,Callable是類似於Runnable的接口,實現Callable接口的類和實現Runnable的類
都是可被其他線程執行的任務。

Callable的接口定義如下:

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

CallableRunnable的區別如下:

I    Callable定義的方法是call,而Runnable定義的方法是run

II   Callablecall方法可以有返回值,Runnablerun方法不能有返回值

III  Callablecall方法可拋出異常,而Runnablerun方法不能拋出異常。

Future 介紹

Future表示異步計算的結果,它提供了檢查計算是否完成的方法,以等待計算的完成,並檢索計算的結果。Futurecancel方法可以取消任務的執行,它有一布爾參數,參數爲 true 表示立即中斷任務的執行,參數爲 false 表示允許正在運行的任務運行完成。Future的 get 方法等待計算完成,獲取計算結果。

    下面的示例中,我們使用Callable來提交任務,使用Future來得到執行的結果。
public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();  
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
    程序驗證:

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<String> future = threadPool.submit(new Callable<String>() {
            public String call() throws Exception {
                Thread.sleep(2000);
                return "Hello";
            };
        });
		 System.out.println("Wait for result...");
	        try {
	            System.out.println("Get the result:" + future.get());
	        } catch (InterruptedException e) {
	            e.printStackTrace();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        threadPool.shutdown();
	    }
}

運行結果:

Wait for result...
Get the result:Hello


發佈了125 篇原創文章 · 獲贊 50 · 訪問量 112萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章