Java线程池表示一组正在等待作业并重复使用多次的工作线程。
在线程池的情况下,创建一组固定大小的线程。 来自线程池中的线程被拉出并由服务提供者分配作业。 完成作业后,线程再次包含在线程池中。
Java线程池的优点
提供了更好的性能,因为不需要重新创建新线程,所以节省了时间。
实时使用
在Servlet和JSP中使用,容器创建一个线程池来处理请求。
Java线程池的示例
下面来看看使用ExecutorService
和Executors
的java线程池的简单示例。
文件: WorkerThread.java
package com.zyiz; 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.zyiz; 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