![](/img/trans.png)
[英]Java Producer Consumer - Why not a simple FixedThreadPool?
[英]Why FixedThreadPool not working properly
這是我的以下代碼:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Start"+" "+Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End!"+" "+Thread.currentThread().getName());
}
}
});
executor.shutdown();
executor.awaitTermination(1, TimeUnit.SECONDS);
這是我的輸出:
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
Start pool-1-thread-1
End! pool-1-thread-1
我的理解是,在我的代碼中, FixedThreadPool
有5
線程。 因此,當我運行代碼時,應該輸出所有5
線程,對嗎? 還是我誤會了什么?
在我的輸出thread-1
每次都開始和結束,但是當它循環for
循環時,它不是應該輸出所有5
線程嗎? 原因是如果只有1個thread
在執行task
那為什么還要5個threads
呢? 所有5
線程都可以在控制台上輸出任何方式嗎?(我是新手)
您只發布了一個Runnable
因此您的ExecutorService
運行了一項任務。 它只會使用一個線程。 要使用多個線程,您必須多次調用submit
,或者可以使用可運行對象的Collection
調用invokeAll
。
編輯
像這樣:
public void test() {
int numberOfThreads = 5;
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
for(int i=0; i<numberOfThreads; i++){
executorService.submit(createRunnable());
}
}
private Runnable createRunnable() {
return new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Start" + " " + Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End!" + " " + Thread.currentThread().getName());
}
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.