Callable的兩種實現方式

Callable的兩種實現方式

使用線程池

package com.edgar.lesson01;

import java.util.concurrent.*;

//建立線程方式:1.實現Callable類 2.重寫call()方法 3.看main方法註釋
public class TestCallable implements Callable<Boolean> {
    @Override
    public Boolean call() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我在看代碼" + i);
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestCallable testCallable = new TestCallable();
        //1.建立執行服務
        ExecutorService es = Executors.newFixedThreadPool(1);
        //2.執行提交
        Future<Boolean> r1 = es.submit(testCallable);
        //3.獲取結果
        Boolean res = r1.get();
        System.out.println(res);
        //4,關閉服務
        es.shutdown();
        
    }
}

使用FutureTask包裝

package com.edgar.lesson01;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//建立線程方式:1.實現Callable類 2.重寫call()方法 3.看main方法註釋
public class TestCallable2 implements Callable {
    @Override
    public Integer call() throws Exception {
        System.out.println("實現Callable接口");
        return 100;
    }

    public static void main(String[] args) {
        TestCallable2 testCallable = new TestCallable2();
        //建立多個FutureTask對象,才能屢次執行線程
        FutureTask futureTask = new FutureTask(testCallable);
        FutureTask futureTask2 = new FutureTask(testCallable);
        new Thread(futureTask).start();
        new Thread(futureTask2).start();
        try {
            System.out.println(futureTask.get());
            System.out.println(futureTask2.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
相關文章
相關標籤/搜索