package com.jikuan.zjk.future;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
/**
* 试验 Java 的 Future 用法
* jikuan.zjk
*/
public class FutureTest {
public static class Task implements Callable {
public String call() throws Exception {
String tid = String.valueOf(Thread.currentThread().getId());
System.out.printf("Thread#%s : in call\n", tid);
return tid;
}
}
static Callable test3 = new Callable() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
};
public static void main(String[] args) throws InterruptedException, ExecutionException {
// test 1
List> results = new ArrayList>();
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++)
results.add(es.submit(new Task()));
// get是阻塞的,等待有返回到Future中才会继续
for (Future res : results)
System.out.println(res.get());
// test 2
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future future = threadPool.submit(new Callable() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
});
System.out.println(future.get());
// test 3
ExecutorService fixThreadPool = Executors.newFixedThreadPool(1);
Future future2 = fixThreadPool.submit(test3);
System.out.println(future2.get());
}
}