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();
        }
    }
}
posted @ 2021-04-15 23:56  EdgarStudy  阅读(601)  评论(0编辑  收藏  举报