package Juc;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
/**
* Callable与runable接口区别:
* runable的run方法出错会直接抛异常,没有返回值
* Callable有返回值,不抛异常可以try catch
*
*/
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {//?
System.out.println("come in Callable");
try{TimeUnit.SECONDS.sleep(5);}catch (Exception e){e.printStackTrace();}
return 1024;//?
}
}
public class CallableDemo {
public static void main(String[] args) throws Exception, ExecutionException {
FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
//FutureTask<Integer> futureTask2 = new FutureTask<>(new MyThread());只执行二次
Thread t1= new Thread(futureTask,"aa");
Thread t2= new Thread(futureTask,"bb"); //只执行一次
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName()+"\t ");
while(!futureTask.isDone()){
}
//System.out.println("***************result :"+futureTask.get());main阻塞
System.out.println(Thread.currentThread().getName()+"\t ");
System.out.println("***************result :"+futureTask.get());
}
}
Callable接口与runable和Thread类
最新推荐文章于 2021-12-04 17:53:39 发布