2017-05-09 74 views
0

我有兩個整數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 
+2

如果你想要的一切,同步運行,目前尚不清楚線程池的目的是什麼。沒有什麼能夠以你的方式平行運行。 –

+1

這並非如何併發工作 – MadProgrammer

+1

我永遠不會爲我的生活理解爲什麼人們在想要順序執行時使用線程。 – EJP

回答

1

你的WorkerThread對象由線程池中的不同線程運行。這些線程獨立運行,所以有些可能會更快地完成運行,而有些則會更慢。這就是爲什麼這些數字沒有按順序排列。

如果你想要的數字是爲了最簡單的方法就是運行它們都在你的主線程,而不是使用一個線程池。或者,您可以創建一個帶有固定線程池的ExecutorService,其中只有一個線程。

1

所以,你有問題,你是越來越y爲了遞減

原因很簡單。您預計首先開始的線程應該先完成。但在線程執行,這樣的事情是不能保證

這一切都取決於每個線程得到如何分配資源。

根據您的要求,您所需要的是一個順序程序,而不是並行。與線程並行的程序,在你的情況下是完全不相關的。

希望這會有所幫助。 :))

+0

你可以告訴我如何使用或不使用線程池。例如程序鏈接或其他東西。 –

+0

@ Mahela.Prasad如果你只是想看到遞減,只需要運行一個for循環從1000到0. –

+0

@ Supun.Wijerathne我想使用x線程數。我認爲threadpool對它很有好處。沒有它,我不知道該怎麼辦。 –