Java線程池
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