java - 线程池按顺序运行

标签 java multithreading threadpool

我有两个整数 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/

相关文章:

java - GWT Google Visualization - 随后的重绘会改变 Y 轴步数吗?

c# - MonoTouch - 线程

c++ - 如何使用Win32线程池API?

java - 代码突出显示为语法错误。为什么?

java - 导入 javax.annotation.PostConstruct 无法解析

c - 在函数调用期间结构更改的 union 内的结构

c++ - 线程合并排序给出无效结果

java - 缓存线程池如何重用现有线程

java - 如何在selenium框架中的不同类之间传递相同的浏览器实例

python - 在多线程应用程序中使用 mongodb 的正确方法