Java執行緒池表示一組正在等待作業並重複使用多次的工作執行緒。
線上程池的情況下,建立一組固定大小的執行緒。 來自執行緒池中的執行緒被拉出並由服務提供者分配作業。 完成作業後,執行緒再次包含線上程池中。
Java執行緒池的優點
提供了更好的效能,因為不需要重新建立新執行緒,所以節省了時間。
實時使用
在Servlet和JSP中使用,容器建立一個執行緒池來處理請求。
Java執行緒池的範例
下面來看看使用ExecutorService
和Executors
的java執行緒池的簡單範例。
檔案: WorkerThread.java
package com.yiibai;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s) {
this.message = s;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " (Start) message = " + message);
processmessage();// call processmessage method that sleeps the thread for 2 seconds
System.out.println(Thread.currentThread().getName() + " (End)");// prints thread name
}
private void processmessage() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
檔案: WorkerThread.java
package com.yiibai;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);//calling execute method of ExecutorService
}
executor.shutdown();
while (!executor.isTerminated()) { }
System.out.println("Finished all threads");
}
}
執行上面範例程式碼,得到以下結果:
pool-1-thread-2 (Start) message = 1
pool-1-thread-4 (Start) message = 3
pool-1-thread-5 (Start) message = 4
pool-1-thread-3 (Start) message = 2
pool-1-thread-1 (Start) message = 0
pool-1-thread-5 (End)
pool-1-thread-2 (End)
pool-1-thread-4 (End)
pool-1-thread-1 (End)
pool-1-thread-3 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (Start) message = 7
pool-1-thread-2 (Start) message = 5
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (Start) message = 9
pool-1-thread-3 (End)
pool-1-thread-5 (End)
pool-1-thread-4 (End)
pool-1-thread-1 (End)
pool-1-thread-2 (End)
Finished all threads