java – 订购线程以创建/启动的顺序运行
发布时间:2020-12-14 17:44:23 所属栏目:Java 来源:网络整理
导读:我如何按照他们实例化的顺序订购线程.我如何使下面的程序按顺序打印数字1 … 10. public class ThreadOrdering { public static void main(String[] args) { class MyRunnable implements Runnable{ private final int threadnumber; MyRunnable(int threadn
我如何按照他们实例化的顺序订购线程.我如何使下面的程序按顺序打印数字1 … 10.
public class ThreadOrdering { public static void main(String[] args) { class MyRunnable implements Runnable{ private final int threadnumber; MyRunnable(int threadnumber){ this.threadnumber = threadnumber; } public void run() { System.out.println(threadnumber); } } for(int i=1; i<=10; i++){ new Thread(new MyRunnable(i)).start(); } } } 解决方法
听起来像你想要的
ExecutorService.invokeAll,它会以固定的顺序返回工作线程的结果,尽管它们可以按任意顺序排列:
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 ThreadOrdering { static int NUM_THREADS = 10; public static void main(String[] args) { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); class MyCallable implements Callable<Integer> { private final int threadnumber; MyCallable(int threadnumber){ this.threadnumber = threadnumber; } public Integer call() { System.out.println("Running thread #" + threadnumber); return threadnumber; } } List<Callable<Integer>> callables = new ArrayList<Callable<Integer>>(); for(int i=1; i<=NUM_THREADS; i++) { callables.add(new MyCallable(i)); } try { List<Future<Integer>> results = exec.invokeAll(callables); for(Future<Integer> result: results) { System.out.println("Got result of thread #" + result.get()); } } catch (InterruptedException ex) { ex.printStackTrace(); } catch (ExecutionException ex) { ex.printStackTrace(); } finally { exec.shutdownNow(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- java.lang.ClassNotFoundException: org.springframework.w
- 为什么javac为两个看似非常相似的结构生成不同的字节代码?
- java – 为什么ThreadPoolExecutor具有BlockingQueue作为参
- java – 有效用户的Tomcat安全性约束
- java – 用Mockito测试Thymeleaf自定义方言
- vagrant 虚拟机搭建 以及virtualbox 安装 配置
- java – JAXB使用扩展对象工厂扩展生成的代码 – 显式转换好
- 阿里P8 Java高级架构师,都需要掌握哪些技术栈?
- 对Java中JSON解析器的一些见解
- Java 抽象类定义与方法实例详解