5. Implement the Callable interface

  • Java 5.0 provides a new way to create execution threads in java.util.Concurrent: the Callable interface

  • The Callable interface is similar to Runnable in that both are designed for classes whose instances might be executed by another thread. Runnable, however, does not return results and cannot throw checked exceptions.

  • Callable relies on FutureTask, which can also be used as a lock

Create thread execution method 3: implement Callable interface. Methods can return values and throw exceptions in contrast to the way the Runnable interface is implemented.

2. Perform Callable, need FutureTask implementation class support, used to receive operation results. FutureTask is the implementation class for the Future interface, and FutureTask can be used for latching

class ThreadDemo implements Callable<Integer> {

    @Override
    public Integer call(a) throws Exception {
        int num = 0;
        for (int i = 0; i < 100000; i++) {
            num += i;
        }
        returnnum; }}Copy the code

test

    public static void main(String[] args) {
        ThreadDemo td = new ThreadDemo();

        //1. Perform Callable, FutureTask implementation class support, used to receive operation results.
        FutureTask<Integer> result = new FutureTask<>(td);

        new Thread(result).start();;

        //2. Receive the result of the thread operation
        try {
            //FutureTask can be used for latching
            Integer num = result.get();
            System.out.println(num);
            System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch(ExecutionException e) { e.printStackTrace(); }}Copy the code