?
class="java" name="code">import java.util.ArrayList; import java.util.List; 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 { // 异步 木桶原理 public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newCachedThreadPool(); int num = 5; System.out.println(System.currentTimeMillis()); List<Future<String>> resultList = new ArrayList<Future<String>>(); for (int i = 0; i < num; i++) { Future<String> futureTask = executorService.submit(new TaskCallable(i)); resultList.add(futureTask); } System.out.println(System.currentTimeMillis()); for (Future<String> future: resultList) { System.out.println(future.get()); } System.out.println(System.currentTimeMillis()); } public static class TaskCallable implements Callable<String>{ private int taskId; public TaskCallable(int taskId) { this.taskId = taskId; } @Override public String call() throws Exception { Thread.sleep(taskId*1000); return "taskId="+taskId+",time="+System.currentTimeMillis(); } } }
?
?
?
?
?
?
?
?
?
?
?
?
?
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。
?
个人主页:http://knight-black-bob.iteye.com/
?
?
?谢谢您的赞助,我会做的更好!
?