建立線程的另外一種方式:實現Callable接口

在開發中,咱們常常經過new thread或者實現runable接口的方式來建立線程,其實還能夠經過實現Callable接口來建立線程。java

先看一下API文檔中關於Callable的介紹:
Callableweb

咱們能夠看出來,相較於實現Runnable接口的方式,實現Callable接口這種方法能夠有返回值,而且能夠拋出異常。ide

經過實現Callable接口來建立線程,須要依賴FutureTask實現類的支持,用於接收運算結果。svg

測試示例:測試

package com.li.test;

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

/** * 1.相較於實現Runnable接口的方式,方法能夠有返回值,而且能夠拋出異常 * 2.須要依賴FutureTask實現類的支持,用於接收運算結果 */

public class TestCallable {

    public static void main(String[] args) {
        CallableThreadTest ctt = new CallableThreadTest();
        FutureTask<Integer> result = new FutureTask<Integer>(ctt);

        new Thread(result).start();

        Integer sum;
        try {
            sum = result.get();
            System.out.println("-->" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class CallableThreadTest implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int sum = 100;
        System.out.println("CurrentThread-->" + Thread.currentThread());
        Thread.sleep(2000);
        return sum;
    }
}

在線程池中,通常和ExecutorService配合來使用。測試示例:spa

package com.li.test;

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

public class TestCallable {

    public static void main(String[] args) throws InterruptedException,
            ExecutionException {
        System.out.println("主線程開始。。。" + Thread.currentThread());

        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> result = executor.submit(new CallableTask());
        executor.shutdown();
        Integer i = result.get();

        System.out.println("主線程結束。。。");
        System.out.println("主線程獲取子線程結果爲:" + i);
    }
}

class CallableTask implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 100;
        System.out.println("子線程開始計算。。。" + Thread.currentThread());

        Thread.sleep(3000);
        System.out.println("子線程結束計算。。。");
        return sum;
    }
}
相關文章
相關標籤/搜索