Callable接口的使用

package cn.it.cast.Test;

import org.omg.CORBA.Current;

import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import static java.lang.Thread.currentThread;

public class TestNewIo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {

        ThreadDemo td = new ThreadDemo();

        //1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
        FutureTask result = new FutureTask(td);

        new Thread(result).start();

        //2.接收线程运算后的结果
        Integer sum = result.get();  //FutureTask 可用于 闭锁 类似于CountDownLatch的作用,在所有的线程没有执行完成之后这里是不会执行的
        System.out.println(sum);
        System.out.println("------------------------------------");
    }
}

class ThreadDemo implements Callable {

    @Override
    public Integer call() throws Exception {

        int sum = 0;

        for (int i = 0; i <= 10; i++) {
            sum += i;
            System.out.println(currentThread().getName()+i);
        }

        return sum;
    }

}

 

你可能感兴趣的:(Callable接口的使用)