zl程序教程

您现在的位置是:首页 >  .Net

当前栏目

使用Callable和Future创建线程

2023-02-18 16:45:17 时间

前言

从Java 5开始,Java提供了Callable接口,该接口是Runnable接口的增强版,Callable接口提供了一个call()方法,可以看作是线程的执行体,但call()方法比run()方法更强大, call()方法可以有返回值,call()方法可以声明抛出异常。

使用代码

public class ThreadCallable implements Callable<Integer> {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadCallable threadCallable = new ThreadCallable();
        FutureTask<Integer> integerFutureTask = new FutureTask<>(threadCallable);
        new Thread(integerFutureTask).start();
        Integer result = integerFutureTask.get();
        System.out.println(result);
    }

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + ",执行计算操作");
        Thread.sleep(3000);
        return 1;
    }
}

总结

Callable和Future 线程可以获取到返回结果,底层基于LockSupport,在执行integerFutureTask.get()方法时,使用LockSupport,先阻塞主线程,子线程执行完毕之后再唤醒主线程。