获取多线程的方式-Callable

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

/**
 * 2022/6/30 4:26 下午
 * 获取多线程的方式
 */
class TestService implements Callable {
    @Override
    public Integer call() throws Exception {
        System.out.println("********come in callable");
        return 1024;
    }

}

class CallableDemo {

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

        FutureTask futureTask = new FutureTask<>(new TestService());

        new Thread(futureTask, "AA").start();
        //不会执行call方法,会直接复用,如果要调用,需要重新new FutureTask
//        new Thread(futureTask, "BB").start();

        int aa = 100;
        while (!futureTask.isDone()){
            //还没执行完、等待
        }
        //建议放后面获取,以免线程堵塞
        int bb = futureTask.get();

        System.out.println("*****result" + (aa+bb));
    }
}

你可能感兴趣的:(获取多线程的方式-Callable)