在Java5之前,线程是没有返回值的,常常为了“有”返回值,破费周折,而且代码很不好写。或者干脆绕过这道坎,走别的路了。
现在Java终于有可返回值的任务(也可以叫做线程)了。
可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。
执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了。
-
package net.spring.utils;
-
-
import java.util.concurrent.Callable;
-
-
public
class CallableThread implements Callable<String> {
-
private String str;
-
-
public CallableThread(String str) {
-
this.str = str;
-
}
-
-
// 需要实现Callable的Call方法
-
public String call() throws Exception {
-
if(
"线程1".equals(str)){
-
Thread.sleep(
1000);
-
}
-
-
String rStr = str +
":hello";
-
System.out.println(str);
-
return rStr;
-
}
-
}
-
package net.spring.utils;
-
-
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 CallableTest {
-
-
/**
-
* @param args
-
* @throws ExecutionException
-
* @throws InterruptedException
-
*/
-
public static void main(String[] args) throws InterruptedException,
-
ExecutionException {
-
-
// 线程池
-
ExecutorService pool = Executors.newFixedThreadPool(
10);
-
-
Callable<String> c1 =
new CallableThread(
"线程1");
-
Callable<String> c2 =
new CallableThread(
"线程2");
-
-
// 表示异步计算的结果
-
Future<String> f1 = pool.submit(c1);
-
Future<String> f2 = pool.submit(c2);
-
-
//这里要等线程1运行完,f1.get()得到值后,才会走System.out.println(f2.get());
-
System.out.println(f1.get());
-
System.out.println(f2.get());
-
-
// 关闭线程池
-
pool.shutdown();
-
-
}
-
-
}
运行结果:
-
线程
2
-
线程
1
-
线程
1:hello
-
线程
2:hello