這是我第一次使用Java線程池爲我的新項目,我碰到這個 鏈接http://www.javacodegeeks.com/2013/01/java-thread-pool-example-using-executors-and-threadpoolexecutor.html來了以後,我對這個比較迷茫,這裏是從頁面的代碼,困惑Java的線程池
package com.journaldev.threadpool;
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
this.command=s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+' Start. Command = '+command);
processCommand();
System.out.println(Thread.currentThread().getName()+' End.');
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString(){
return this.command;
}
}
package com.journaldev.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread('' + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println('Finished all threads');
}
}
在代碼中,創建了固定大小的池並創建了10個工作線程,對嗎?
線程池應該可以減輕系統的負擔,相反,在上面的代碼中,我認爲它通過創建池和工作線程來增加負擔。爲什麼還要使用線程池?
任何人都可以解釋嗎? 感謝
我也讀StackOverflow上 http://stackoverflow.com/questions/19765904/how-threadpool-re-use-threads-and-how-it-works 這個帖子並沒有幫助我滿意。
謝謝,這有助於 –