1. 程式人生 > 其它 >Callable、Future和FutureTask

Callable、Future和FutureTask

Callable

  • Runnable沒有返回值:public abstract void run();,Callable可以有返回值:V call() throws Exception;
  • 可以丟擲異常
  • 方法不同,run()/call()
  • 原始碼
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;
}

Future

  • Future只是一個介面
  • 能判斷任務是否完成;能夠中斷任務;能夠獲取任務執行結果。
  • 原始碼
public interface Future<V> {
	// 如果取消已經完成的任務會返回false;如果任務正在執行,若mayInterruptIfRunning設定為true,則返回true,若mayInterruptIfRunning設定為false,則返回false;如果任務還沒有執行,則無論mayInterruptIfRunning為true還是false,肯定返回true。
    boolean cancel(boolean mayInterruptIfRunning);
	// 是否被取消成功
    boolean isCancelled();
    // 是否已經完成
    boolean isDone();
	// 獲取執行結果,這個方法會產生阻塞,會一直等到任務執行完畢才返回
    V get() throws InterruptedException, ExecutionException;
	// 如果在指定時間內,還沒獲取到結果,就直接返回null
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

FutureTask

  • FutureTask是Future介面的一個唯一實現類

  • 繼承關係

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}
public class FutureTask<V> implements RunnableFuture<V> 

RunnableFuture繼承了Runnable介面和Future介面,而FutureTask實現了RunnableFuture介面。所以它既可以作為Runnable被執行緒執行,又可以作為Future得到Callable的返回值。

  • 構造方法
public FutureTask(Callable<V> callable) {
    if (callable == null)
        throw new NullPointerException();
    this.callable = callable;
    this.state = NEW;      
}

public FutureTask(Runnable runnable, V result) {
    this.callable = Executors.callable(runnable, result);
    this.state = NEW;    
}
  • Callable+Future
import java.util.concurrent.*;

class MyCallable {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<Integer> result = executor.submit(task);
        executor.shutdown();

        TimeUnit.SECONDS.sleep(1);

        System.out.println("主執行緒在執行任務");

        try {
            System.out.println("task執行結果" + result.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任務執行完畢");
    }
}

class Task implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("子執行緒在進行計算");
        TimeUnit.SECONDS.sleep(2);
        int sum = 0;
        for (int i = 0; i < 100; i++)
            sum += i;
        return sum;
    }
}
  • Callable+FutureTask
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class MyCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // new Thread(new Runnable()).start();
        // new Thread(new FutureTask<V>()).start();
        // new Thread(new FutureTask<V>( Callable )).start();

        MyThread myThread = new MyThread();
        FutureTask<Integer> integerFutureTask = new FutureTask<>(myThread); // 適配類

        new Thread(integerFutureTask, "A").start();
        new Thread(integerFutureTask, "B").start(); // 結果會被快取,只會列印一個call

        Integer o = integerFutureTask.get(); // 返回值   此方法可能會產生阻塞,最好放在最後一行
        System.out.println(o);
    }
}

class MyThread implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("call()");
        return 7;
    }
}