1. 程式人生 > >創建線程的第三種方式——使用Callable接口

創建線程的第三種方式——使用Callable接口

https err catch lse ble 兩個 tst time ID

Callable是類似於Runnable的接口,實現Callable的類和實現Runnable的類都是可被其他線程執行的任務。

優點:有返回值

缺點:實現繁瑣

簡單實現:

CallableAndFuture.java
/**
 * 簡單實現
 *
 * @author :liuqi
 * @date :2018-06-13 11:10.
 */
public class CallableAndFuture {
    static class MyThread implements Callable<String> {
        @Override
        public String call() throws
Exception { return "Hello world"; } } public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> future = threadPool.submit(new MyThread()); try { System.out.println(future.get()); }
catch (Exception e) { } finally { threadPool.shutdown(); } } }

運行結果:

Hello world

進階:

Race.java
/**
 * 實現callable類
 *
 * @author :liuqi
 * @date :2018-06-13 10:13.
 */
public class Race implements Callable<Integer> {
    private String name;
    private long time;
    
private boolean flag = true; // 步數 private int step = 0; public Race(){ } public Race(String name,int time){ super(); this.name = name; this.time = time; } @Override public Integer call() throws Exception { while(flag){ Thread.sleep(time); step++; } return step; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public int getStep() { return step; } public void setStep(int step) { this.step = step; } }
Demo05.java
/**
 * 使用collable接口創建線程
 *
 * @author :liuqi
 * @date :2018-06-13 10:22.
 */
public class Demo05 {
    public static void main(String[] args) throws InterruptedException,ExecutionException {
        // 創建兩個線程
        ExecutorService ser = Executors.newFixedThreadPool(2);
        Race tortoise = new Race("烏龜",1000);
        Race rabbit = new Race("兔子",500);
        // 獲取future對象
        Future<Integer> result1 = ser.submit(tortoise);
        Future<Integer> result2 = ser.submit(rabbit);
        // 2秒
        Thread.sleep(2000);
        // 停止線程體循環
        tortoise.setFlag(false);
        rabbit.setFlag(false);
        // 獲取值
        int num1 = result1.get();
        int num2 = result2.get();
        System.out.println("烏龜跑了 " + num1 + "步");
        System.out.println("兔子跑了 " + num2 + "步");
        // 停止服務
        ser.shutdownNow();
    }
}

運行結果:

烏龜跑了 3步
兔子跑了 5步

代碼地址:https://github.com/yuki9467/TST-javademo/tree/master/src/main/thread

Callable和Runnable有幾點不同:

1.Callable規定方法是call(),而Runnable規定方法是run();

2.Callable任務執行後可返回值,而Runnable不能返回值;

3.call()可拋出異常,而run()不能拋出異常;

4.運行Callable任務可拿到一個Future對象,Future表示異步計算的結果,通過Future對象可了解任務執行情況,可取消任務的執行,還可獲取任務執行的結果。

創建線程的第三種方式——使用Callable接口