首頁  >  文章  >  Java  >  java中的Future怎麼使用

java中的Future怎麼使用

王林
王林轉載
2023-04-30 23:10:131926瀏覽

說明

1、Future介面代表非同步計算結果,提供檢查計算結果是否完成、取得計算結果等方法。

2、FutureTask類別提供了Future介面的實現,實作了Runnable介面。

實例

public class MyCallable implements Callable<Integer> {
    public Integer call() {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            sum += i;
        }
        return new Integer(sum);
    }
}
public class Demo{
    public static void main(String[] args) {
        MyCallable callable = new MyCallable();
        FutureTask<Integer> result = new FutureTask<Integer>(callable);
        new Thread(result).start();
        try {
            Integer value = result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

以上是java中的Future怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除