java Future用法和意义一句话击破 [转]

2016年11月10日 IT生活 暂无评论
https://www.oschina.net/question/54100_83333
package demo.future;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
 * 试验 Java 的 Future 用法
 */
public class FutureTest {
    public static class Task implements Callable<String> {
        @Override
        public String call() throws Exception {
            String tid = String.valueOf(Thread.currentThread().getId());
            System.out.printf("Thread#%s : in calln", tid);
            return tid;
        }
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        List<Future<String>> results = new ArrayList<Future<String>>();
        ExecutorService es = Executors.newCachedThreadPool();
        for(int i=0; i<100;i++)
            results.add(es.submit(new Task()));
        for(Future<String> res : results)
            System.out.println(res.get());
    }
}
VN:F [1.9.9_1125]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.9_1125]
Rating: 0 (from 0 votes)