Thread pool là tập hợp các thread được khởi tạo trước. Ý tưởng chung là tạo số lượng thread khi khởi động ứng dụng và đặt chúng vào pool, nơi chúng chờ đợi công việc. Khi server nhận request, nó đánh thức một thread từ pool (nếu có) và giao request để xử lý. Khi thread hoàn thành, nó trả về pool chờ việc tiếp theo. Nếu pool không có thread khả dụng, server chờ cho đến khi có thread rảnh.
Điều này tiết kiệm thời gian vì không cần tạo thread mới.
Thường dùng trong Servlet và JSP nơi container tạo thread pool để xử lý request.
Ví dụ
EmployeeThread.java
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class EmployeeThread implements Runnable { private String message; public EmployeeThread(String s) { this.message=s; } public void run() { System.out.println(Thread.currentThread().getName()+" (Start) message = "+message); processmessage();//gọi phương thức ngủ thread 2 giây System.out.println(Thread.currentThread().getName()+" (End)");//in tên thread } private void processmessage() { try { Thread.sleep(1000); } catch (InterruptedException e){ e.printStackTrace(); } } }
ExampleThreadPool.java
public class implementThreadPool { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(6); //tạo pool 6 threads for (int m = 0; m< 6; m++) { Runnable worker = new EmployeeThread("" + i); executor.execute(worker); //gọi execute của ExecutorService } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all the threads"); } }