Java并发编程(四)Future和Callable

Future和Callable

线程Thread 不支持返回值的功能 如果需要返回值可以使用Future 和 Callable。

@AllArgsConstructor
@NoArgsConstructor
public class MyCallable implements Callable<String> {

    private int age;

    @Override
    public String call() throws Exception {
        return "age " + age;
    }

    public static void main(String[] args) {
        try {

            MyCallable myCallable = new MyCallable(24);
            ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 3, 5L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
            Future<String> future = executor.submit(myCallable);
            System.out.println(System.currentTimeMillis());
            String str = future.get();
            System.out.println(str);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

}

在这里插入图片描述

submit() 支持 Callable 和 Runnable 两种方式。

public static void main(String[] args) {
        MyCallable myCallable = new MyCallable(24);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 3, 5L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        Future<?> future = executor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(1234);
            }
        });
        System.out.println(System.currentTimeMillis());
        System.out.println(future.isDone());
    }

在这里插入图片描述

cancel(boolean mayInterruptIfRunning) 如果现车个正在运行则中断正在运行的线程,返回值表示任务取消是否成功。

get(long timeout, TimeUnit unit) 在指定的最大时间内获得返回值。如果超时测抛出异常

自定义异常策略

public class MyRejectedExecution implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            //实现自定义据略逻辑
        }
    }

execute() 方法没有返回值, submit() 方法可以有返回值
默认情况下execute() 直接抛出异常, 可以通过自定义ThreadFactory捕获异常。
submit() 可以catch ExecutionException 捕获异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值