forked from JustinSDK/JavaSE6Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFutureDemo.java
More file actions
33 lines (28 loc) · 991 Bytes
/
FutureDemo.java
File metadata and controls
33 lines (28 loc) · 991 Bytes
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
package onlyfun.caterpillar;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class FutureDemo {
public static void main(String[] args) {
Callable<int[]> primeCallable = new PrimeCallable(1000);
FutureTask<int[]> primeTask = new FutureTask<int[]>(primeCallable);
Thread t = new Thread(primeTask);
t.start();
try {
// 假設現在做其它事情
Thread.sleep(5000);
// 回來看看質數找好了嗎
if(primeTask.isDone()) {
int[] primes = primeTask.get();
for(int prime : primes) {
System.out.print(prime + " ");
}
System.out.println();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}