Callables and Futures

    技术2022-05-19  18

    public interface Callable<V>

    {

       V call() throws Exception;

    }

     

    public interface Future<V>

    {

       V get() throws . . .;

       V get(long timeout, TimeUnit unit) throws . . .;

       void cancel(boolean mayInterrupt);

       boolean isCancelled();

       boolean isDone();

    }

    无参数的get方法会一直blocked直到计算完成,有参数如果时间到了还没完成,则抛出TimeoutException。他们两个都会抛出  InterruptedException

    cancel方法试图中止任务线程。如果线程还没有start()那么它永不会开始,如果已经开始并且cancel的参数为true,则会调用interrupt()方法来中止

    Callable<Integer> myComputation = . . .;

    FutureTask<Integer> task = new FutureTask<Integer>(myComputation);

    Thread t = new Thread(task); // it's a Runnable

     

    t.start();

    . . .

    Integer result = task.get(); // it's a Future


    最新回复(0)