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 { // Asynchronous barrel principle 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(); } } }
Donate to developers
Driven by interest, I write 免费
something with joy and sweat. I hope you like my work and can support it at the same time. Of course, if you have money to support a money field (support Alipay, WeChat, and the buckle group), if you have no money to support a personal field, thank you.
Personal homepage : http://knight-black-bob.iteye.com/
Thank you for your sponsorship, I will do better!