- package com.yuxue.juc.threadPool;
-
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.FutureTask;
-
- /**
- * 多线程中,第三种获得多线程的方式
- * */
- public class CallableTest {
- public static void main(String[] args) throws ExecutionException, InterruptedException {
- //FutureTask(Callable<V> callable)
- FutureTask<Integer> futureTask = new FutureTask<>(new myThread());
-
- new Thread(futureTask, "AAA").start();
- //new Thread(futureTask, "BBB").start();//复用,直接取值,不要重启两个线程
- int a = 100;
- int b = 0;
- //b = futureTask.get();//要求获得Callable线程的计算结果,如果没有计算完成就要去强求,会导致堵塞,直到计算完成
- while (!futureTask.isDone()) {
- 当futureTask完成后取值
- b = futureTask.get();
- }
- System.out.println("===Result is:" + (a + b));
- }
- }
-
- class myThread implements Callable<Integer> {
- @Override
- public Integer call() throws Exception {
- System.out.println(Thread.currentThread().getName() + "\tget in the callable");
- Thread.sleep(5000);
- return 1024;
- }
- }
两者区别: