JAVA支持有返回值的线程是在JAVA5及之后的版本。
获取线程返回值需要实现Callable接口。
具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| 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;
public class GetResultOfThread {
public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService pool = Executors.newFixedThreadPool(3);
Callable c1 = new GetResult("c1"); Callable c2 = new GetResult("c2");
Future f1 = pool.submit(c1); Future f2 = pool.submit(c2);
System.out.println(f1.get().toString()); System.out.println(f2.get().toString());
pool.shutdown();
}
}
class GetResult implements Callable { private String oid;
public GetResult(String oid) { this.oid = oid; }
@Override public Object call() throws Exception { return oid + ":任务返回的内容"; }
}
|