1. 程式人生 > >安卓複習之旅—Thread、Runnable、Callable、Futrue類關係與區別

安卓複習之旅—Thread、Runnable、Callable、Futrue類關係與區別

開啟一個執行緒有三種方式定義:

Thread、Runnable、Callable,其中Runnable實現的是void run()方法,Callable實現的是 V call()方法,並且可以返回執行結果,其中Runnable可以提交給Thread來包裝下,直接啟動一個執行緒來執行,而Callable則一般都是提交給ExecuteService來執行。

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; }

簡單來說,Executor就是Runnable和Callable的排程容器,Future就是對於具體的排程任務的執行結果進行檢視,最為關鍵的是Future可以檢查對應的任務是否已經完成,也可以阻塞在get方法上一直等待任務返回結果。Runnable和Callable的差別就是Runnable是沒有結果可以返回的,就算是通過Future也看不到任務排程的結果的。


public interface Future<V> {  


    boolean cancel(boolean mayInterruptIfRunning);  

   n isCancelled();  


    boolean isDone();  

       V get() throws InterruptedException, ExecutionException;  


    V get(long timeout, TimeUnit unit)  
        throws InterruptedException, ExecutionException, TimeoutException;  
}

future的get和cancle小例子:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadDemo {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    // 建立一個執行任務的服務
    ExecutorService service = Executors.newFixedThreadPool(3);
    try {
        // 1.Runnable通過Future返回結果
        // 建立一個Runnable,來排程,等待任務執行完畢,取得返回結果
        Future<?> runable = service.submit(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                System.out.println("runable is running");
            }
        });
        System.out.println("runable.get():" + runable.get());

        // 2.Callable通過Future能返回結果
        // 提交併執行任務,任務啟動時返回了一個 Future物件,
        // 如果想得到任務執行的結果或者是異常可對這個Future物件進行操作
        Future<String> callable = service.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                // TODO Auto-generated method stub
                System.out.println("callable is running");
                return "result is callable";
            }
        });
        System.out.println("callable.get():" + callable.get());
        // 3. 對Callable呼叫cancel可以對對該任務進行中斷
        // 提交併執行任務,任務啟動時返回了一個 Future物件,

        Future<String> callable2 = service.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                // TODO Auto-generated method stub
                try {
                    while (true) {
                        System.out.println("callable2 is running.");
                        Thread.sleep(50);
                    }
                } catch (InterruptedException e) {
                    System.out.println("Interrupted callable2.");
                }
                return "result is callable2";
            }
        });
        // 等待5秒後,再停止第二個任務。因為第二個任務進行的是無限迴圈
        Thread.sleep(10);
        System.out.println("callable2 cancle: " + callable2.cancel(true));

        // 4.用Callable時丟擲異常則Future什麼也取不到了
        // 獲取第三個任務的輸出,因為執行第三個任務會引起異常
        // 所以下面的語句將引起異常的丟擲
        Future<String> callable3 = service.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                throw new Exception("callable3 throw exception!");
            }

        });
        System.out.println("task3: " + callable3.get());

        // 停止任務執行服務
        service.shutdownNow();

    } catch (Exception e) {
          System.out.println(e.toString());  
    }
}

}
執行結果:

runable is running
runable.get():null
callable is running
callable.get():result is callable
callable2 is running.
callable2 cancle: true
Interrupted callable2.
java.util.concurrent.ExecutionException: java.lang.Exception: callable3 throw exception!

FutureTask實現RunnableFuture,即實現了Runnbale又實現了Futrue這兩個介面,另外它還可以包裝Runnable和Callable,所以一般來講是一個複合體了,它可以通過Thread包裝來直接執行,也可以提交給ExecuteService來執行,並且還可以通過v get()返回執行結果,線上程體沒有執行完成的時候,主執行緒一直阻塞等待,執行完則直接返回結果。

public class FutureTask<V> implements RunnableFuture<V> 

public interface RunnableFuture<V> extends Runnable, Future<V> {  
    /** 
     * Sets this Future to the result of its computation 
     * unless it has been cancelled. 
     */  
    void run();  
}  

futuretask例子:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class FutureTaskDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Callable<String> callable = new Callable<String>() {

            @Override
            public String call() throws Exception {
                // TODO Auto-generated method stub
                System.out.println("Sleep start.");
                Thread.sleep(1000 * 2);
                System.out.println("Sleep end.");
                return "time=" + System.currentTimeMillis();
            }
        };

        try {
            // 直接使用Thread的方式執行
            FutureTask<String> ft = new FutureTask<>(callable);
            new Thread(ft).start();
            System.out.println("ft.get() = " + ft.get());


            FutureTask<String> ft2 = new FutureTask<>(callable);

            // 使用Executors來執行
            System.out.println("=========");
            Executors.newSingleThreadExecutor().submit(ft2);
            System.out.println("ft2.get() = " + ft2.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

}

執行結果:

Sleep start.
Sleep end.
ft.get() = time=1481081318178
=========
Sleep start.
Sleep end.
ft2.get() = time=1481081320188