Runnable
和Thread
都没有返回值,如果想要在线程结束后有返回值,需要Callable
接口。Callable
是个支持泛型的接口,我们是实现这个接口的时候可以指定返回值得类型。
其实我们还需要一个支持取得返回值得方式,并且实现了Runnable
的类。这个类就是FutureTask
。FutureTask
就是一个Runnable
,因此可以调用Thread的start()方法运行它。
例子:
package thread;
import java.text.SimpleDateFormat;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
Thread.sleep(1000*10);
return "OK";
}
}
public class TestCallable {
public static void main(String[] args) {
FutureTask<String> featureTask =new FutureTask<String>(new MyCallable());
new Thread(featureTask).start();
System.out.println(formatDate(System.currentTimeMillis()));
try {
System.out.println("The result is "+ featureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(formatDate(System.currentTimeMillis()));
}
private static String formatDate(long date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return simpleDateFormat.format(date);
}
}
执行结果:
2017/06/22 22:39:12
The result is OK
2017/06/22 22:39:22
从结果看到,get()方法是个同步方法,会阻塞程序执行。
另一种有返回值的方式就是 executorService.submit()
,submit
一个实现Callable
接口的类就行,这种方式get也是会阻塞的。
package thread;
import java.text.SimpleDateFormat;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(1000 * 10);
return "OK";
}
}
public class TestCallable {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
Future<String> future = executorService.submit(new MyCallable());
System.out.println(formatDate(System.currentTimeMillis()));
try {
System.out.println("The result is " + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(formatDate(System.currentTimeMillis()));
}
private static String formatDate(long date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return simpleDateFormat.format(date);
}
}
结果相似,只是时间不同