스레드 풀은 미리 초기화된 스레드의 모음입니다. 스레드 풀 뒤에 있는 일반적인 계획은 메서드 시작 시 다양한 스레드를 형성하고 작업이 예상되는 위치에 있는 풀에 배치하는 것입니다. 서버가 참여 요청을 받으면 이 풀(사용 가능한 경우)에서 스레드를 깨우고 서비스 요청을 전달합니다. 스레드가 서비스를 완료하면 풀로 돌아가 많은 작업을 기다립니다. 풀에 액세스 가능한 스레드가 없으면 서버는 스레드가 해제될 때까지 기다립니다.
새 스레드를 생성할 필요가 없으므로 시간이 절약됩니다.
도구가 요청을 처리하기 위해 스레드 풀을 생성하는 모든 곳에서 Servlet 및 JSP에서 활용됩니다.
예시
EmployeeThread.java
importjava.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();//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(1000);
}
catch (InterruptedException e){
e.printStackTrace(); }
}
} ExampleThreadPool.java
public class implementThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(6); //creating a pool of 6 threads
for (int m = 0; m< 6; m++) {
Runnable worker = new EmployeeThread("" + i);
executor.execute(worker); //calling execute method of ExecutorService
}
executor.shutdown();
while (!executor.isTerminated()) { }
System.out.println("Finished all the threads");
}
}