以前说实现线程都是说有两种方法,一种继承Thread 另一种是实现Runable 接口,不过这种线程的都不能有返回值,而有时候需要返回值。这时候实现callable 接口是个不错的选择。
package com.quartz.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableThread implements Callable<Object> {
@Override
public Object call() throws Exception {
// TODO Auto-generated method stub
return "有返回值的线程";
}
public static void main(String[] args) {
Callable<Object> c = new CallableThread();
Future<Object> f1 = Executors.newCachedThreadPool().submit(c);
try {
System.out.println(f1.get().toString());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}