Home  >  Article  >  Java  >  How to use Future in java

How to use Future in java

王林
王林forward
2023-04-30 23:10:131986browse

Explanation

1. The Future interface represents the asynchronous calculation result and provides methods to check whether the calculation result is completed and obtain the calculation result.

2. The FutureTask class provides the implementation of the Future interface and implements the Runnable interface.

Example

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();
        }
    }
}

The above is the detailed content of How to use Future in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete