Callable和Runable相比
//Runnable和Callable区别
//1.Callable带返回值
//2.run()不会抛异常,call()会抛异常
//3.实现的接口不同
package JUC;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;/*** 多线程中第三种活动线程的方法*///Runnable和Callable区别
//1.Callable带返回值
//2.run()不会抛异常,call()会抛异常
//3.接口实现的接口不同//class MyThread implements Runnable{
// @Override
// public void run() {
//
// }
//}
class MyThread2 implements Callable{@Overridepublic Integer call() throws Exception {System.out.println(Thread.currentThread().getName()+"\t come in callable");TimeUnit.SECONDS.sleep(3);return 1024;}
}
//适配器模式//并发异步导致callable出现,
public class CallableDemo {public static void main(String[] args) throws ExecutionException, InterruptedException {FutureTask<Integer> futureTask = new FutureTask<>(new MyThread2());FutureTask<Integer> futureTask1 = new FutureTask<>(new MyThread2());new Thread(futureTask,"AA").start();//new Thread(futureTask,"BB").start();//不会再进入callable,因为可以复用,所以没必要在进入一次,想多算就需要多启动futureTasknew Thread(futureTask1,"BB").start();int result1 = 100;//int result = futureTask.get();//获得callable线程的结算结果,如果没有计算完成就要去强求,会导致堵塞,直到计算完成,// 如果现在去取futureTask.get()结果那么main线程就会堵塞,因为没计算完,所以放到最后会先让main线程执行,最后再去取callable线程结果int result = futureTask.get();System.out.println("*******result:"+(result+result1));}
}