我有两个整数 x 和 y。 x 是线程池中的线程数。 y 是我想要运行线程的次数。我不想使用 sleep()。
public class TestThreadPool {
public static void main(String[] args) {
int x = 7;
int y = 1000;
ExecutorService executor = Executors.newFixedThreadPool(x);//creating a pool of 7 threads
for (int i = 0; i < y; i++) {
Runnable worker = new WorkerThread("" + (y-i));
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) { }
System.out.println("Finished all threads");
}
}
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s){
this.message=s;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" count = " + message);
}
}
当我运行这个时,我得到这个 -->
pool-1-thread-1 count = 1000
pool-1-thread-3 count = 998
pool-1-thread-2 count = 999
pool-1-thread-4 count = 997
.
.
.
.
pool-1-thread-2 count = 2
pool-1-thread-15 count = 1
pool-1-thread-14 count = 7
pool-1-thread-4 count = 8
pool-1-thread-3 count = 9
Finished all threads
我的问题是:我想要输出、线程并按顺序计数。 像这样-->
pool-1-thread-1 count = 1000
pool-1-thread-2 count = 999
pool-1-thread-3 count = 998
pool-1-thread-4 count = 997
pool-1-thread-5 count = 996
pool-1-thread-6 count = 995
pool-1-thread-7 count = 994
pool-1-thread-1 count = 993
pool-1-thread-2 count = 992
.
.
pool-1-thread-5 count = 2
pool-1-thread-6 count = 1
Finished all threads
最佳答案
您的 WorkerThread 对象由线程池中的不同线程运行。线程独立运行,因此有些线程可能会更快地完成运行工作程序,而有些线程可能会较慢。这就是为什么数字没有按顺序出现的原因。
如果您希望数字按顺序排列,最简单的方法就是在主线程中运行它们,而不是使用线程池。或者,您可以创建一个带有固定线程池且其中只有一个线程的 ExecutorService。
关于java - 线程池按顺序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43859462/