线程池是预初始化线程的集合。线程池背后的总体计划是在方法启动时形成各种线程,并将它们放入池中,无论它们位于何处并期望工作。服务器接收到参与请求后,就会从该池中唤醒一个线程(如果有),然后将服务请求传递给该线程。线程完成其服务后,它将返回到池中并等待大量工作。如果池中没有可访问的线程,则服务器将等到其中一个空闲。
由于不需要产生新线程,因此可以节省时间。
在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"); } }