Java5以后,出现有返回值的多线程。
实现方式:实现Callable接口,无返回值的实现Runnable接口。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
MyCallable c1 = new MyCallable("A");
MyCallable c2 = new MyCallable("B");
Future<Object> f1 = pool.submit(c1);
Future<Object> f2 = pool.submit(c2);
System.out.println("---->" + f1.get().toString());
System.out.println("---->" + f2.get().toString());
pool.shutdown();
}
}
class MyCallable implements Callable<Object> {
private String oid;
public MyCallable(String oid) {
super();
this.oid = oid;
}
@Override
public Object call() throws Exception {
return oid + "任务返回的内容";
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/5c2b02ec29eca7ba82226e3369e6c5a7.jpeg)