线程池-Callable接口(2)

Callable接口

Callable接口与Runnable接口的区别:

  1. Callable接口中call方法有返回值,Runnable接口中run方法没有返回值
  2. Callable接口中call方法有声明异常,Runnable接口中run方法没有声明异常
单词单词
CallableFutureTask(执行任务)与Callable配合
package dey01;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//例子:实现1-100和
public class Callable_01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.创建一个Callable对象
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName()+"-----开始-----");
                int sum = 0;
                for (int i = 1; i <= 100; i++) {
                    sum += i;
                }
                return sum;
            }
        };
        //2.把Callable对象 转成可执行任务
        FutureTask<Integer> task = new FutureTask<Integer>(callable);
        //3.创建线程
        Thread thread = new Thread(task);
        //4.启动线程
        thread.start();
        //5.获取结果
        Integer sum = task.get();
        System.out.println(sum);
    }
}

Callable与线程池配合 代码

package dey01;
import java.util.concurrent.*;
//Future 表示将要执行完任务的结果
//例子:实现1-100和
public class Callable_01 {
    public static void main(String[] args) throws Exception{
        //1.创建一个线程池和Callable对象
        ExecutorService es = Executors.newSingleThreadExecutor();
        //2.提交任务
        Future<Integer> future = es.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName()+"-----开始-----");
                int sum = 0;
                for (int i = 1; i <= 100; i++) {
                    sum += i;
                }
                return sum;
            }
        });
        //3.获取任务结果
        System.out.println(future.get());
        //4.关闭线程
        es.shutdown();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值