本文轉自http://www.cnblogs.com/linjiqin/p/3213809.html 感謝作者
在Java5之前,線程是沒有返回值的,常常為了“有”返回值,破費周折,而且代碼很不好寫。或者干脆繞過這道坎,走別的路了。
現在Java終於有可返回值的任務(也可以叫做線程)了。
可返回值的任務必須實現Callable接口,類似的,無返回值的任務必須Runnable接口。
執行Callable任務后,可以獲取一個Future的對象,在該對象上調用get就可以獲取到Callable任務返回的Object了。
下面是個很簡單的例子:
|
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
42
43
44
45
|
package
com.ljq.test.thread;
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
CallableFutureTest {
@SuppressWarnings
(
"unchecked"
)
public
static
void
main(String[] args)
throws
ExecutionException,
InterruptedException {
CallableFutureTest test =
new
CallableFutureTest();
// 創建一個線程池
ExecutorService pool = Executors.newFixedThreadPool(
2
);
// 創建兩個有返回值的任務
Callable c1 = test.
new
MyCallable(
"A"
);
Callable c2 = test.
new
MyCallable(
"B"
);
// 執行任務並獲取Future對象
Future f1 = pool.submit(c1);
Future f2 = pool.submit(c2);
// 從Future對象上獲取任務的返回值,並輸出到控制台
System.out.println(
">>>"
+ f1.get().toString());
System.out.println(
">>>"
+ f2.get().toString());
// 關閉線程池
pool.shutdown();
}
@SuppressWarnings
(
"unchecked"
)
class
MyCallable
implements
Callable {
private
String name;
MyCallable(String name) {
this
.name = name;
}
public
Object call()
throws
Exception {
return
name +
"任務返回的內容"
;
}
}
}
|
>>>A任務返回的內容 >>>B任務返回的內容
