我很好奇如何让线程使用join()
顺序打印出来。(也欢迎任何其他方式。)例如,我的代码如下:
private static class LittleThread implements Runnable {
int val;
public LittleThread(int i) {
val = i;
}
public void run() {
System.out.println("Thread " + val + " finished.");
}
}
public static void main(String[] args) throws Exception {
for (int i = 1; i <= 10; i++) {
new Thread(new LittleThread(i)).start();
}
}
我想知道,我们如何处理这段代码,依次制作main()
版画:
线程1完成。
线程2完成。
线程3完成。
...
答案 0 :(得分:1)
要生成多个Runnable
个对象,在单独的Thread
中执行,按顺序执行,您应该使用单个帖子this blog post:
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
executor.submit(new LittleThread(i));
}
executor.shutdown();
}
ExecutorService
负责正确管理Thread
个对象(好的,在这种情况下都是其中一个)...根据需要创建它们(it),并通过调用{来终止它们{1}}(当服务关闭时)。