FutureTask

FutureTask也可以用作闭锁;

FutureTask实现了Future语义,表示一种抽象的可生成结果的计算;Future表示的计算是通过Callable来实现,相当于一种可生成结果的Runnable,并且可处于以下三种状态:等待运行,正在运行(Running)和运行完成(Completed);

FutureTask.get的行为取决于任务的状态;如果任务已经完成,那么get会立即返回结果,否则将阻塞直到任务进入完成状态,然后返回结果或抛出异常;

FutureTask将计算结果从执行计算的线程传递到获取这个结果的线程,而FutureTask的规范确保了这种传递过程能实现结果的安全发布;

示例:

public class Appliction {
    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        FutureTask futureTask = new FutureTask(()->{
            Result result = new Result();
            TimeUnit.SECONDS.sleep(10);
            result.setCount(10);
            return result;
        });

        Thread thread = new Thread(futureTask);
        thread.start();
        Result result = (Result) futureTask.get(3,TimeUnit.SECONDS);
        System.err.println(result.getCount());
    }
}
class Result{
    private int count;

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

results matching ""

    No results matching ""