我有兩個整數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
如果你想要的一切,同步運行,目前尚不清楚線程池的目的是什麼。沒有什麼能夠以你的方式平行運行。 –
這並非如何併發工作 – MadProgrammer
我永遠不會爲我的生活理解爲什麼人們在想要順序執行時使用線程。 – EJP