从Runable以及Thread的run方法可以看到,已经限定了没有任何返回值和异常抛出,那么如果想构建一个线程,其运行的方法有异常抛出以及返回值,使用Callable接口,实现call方法,call方法有返回值和异常抛出。
public class MyCallableThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("doing....");
Thread.sleep(3000);
return 1;
}
}
定义完毕MyCallableThread ,如何以线程的方式运行?
MyCallableThread d = new MyCallableThread ();
FutureTask<Integer> task = new FutureTask<>(d);
Thread t = new Thread(task);
t.start();
System.out.println("Do others...");
Integer result = task.get(); //等待
System.out.println("Result:" + result); //1 等待3秒后,返回1
task.get()
会阻塞,等待MyCallableThread线程运行完毕后,拿到结果;通过FutureTask和Thread来启动自定义的MyCallableThread。
原理
//todo
网友评论