Java线程池表示一组正在等待作业并多次重复使用的工作线程。
如果是线程池, 则会创建一组固定大小的线程。服务提供商从线程池中拉出一个线程并为其分配作业。作业完成后, 线程再次包含在线程池中。
Java线程池的优势更好的性能由于无需创建新线程, 因此可以节省时间。
实时使用它用于Servlet和JSP, 其中容器创建线程池来处理请求。
Java线程池示例让我们来看一个使用ExecutorService和Executors的Java线程池的简单示例。
【Java线程池介绍和实例】文件:WorkerThread.java
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();
}
}
}
文件:JavaThreadPoolExample.java
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-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
推荐阅读
- Java多线程介绍
- 线程join()方法
- Java Runtime类
- Java中的线程间通信
- Java中断线程
- win10系统隐藏库文件夹图文详细教程
- 升级Win10后office用不了怎样处理?
- Win10磁盘占用100%处理办法
- Win10蓝屏出错0x0000003B怎样办