简单的Java线程池可以从Executors.newFixedThreadPool( int n)获得。此方法返回一个线程容量为n的线程池。然后ExecutorService的execute执行之。
现给出一个示例。
package zhangphil.executorservice;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ZhangPhilExecutorService {
?// 为了容易理解线程池的概念,假设容量只有2的线程池。
?// 实际使用过程中当然可以更多!
?private final int NUMBER = 2;
?public ZhangPhilExecutorService() {
? // 创建容量为2的线程池。
? ExecutorService pool = Executors.newFixedThreadPool(NUMBER);
? for (int i = 0; i < 10; i++) {
? ?Thread t = new TestThread(i);
? ?System.out.println("线程池执行线程id:" + i);
? ?pool.execute(t);
? }
? // 关闭线程池。
? pool.shutdown();
?}
?private class TestThread extends Thread {
? private int id;
? public TestThread(int id) {
? ?this.id = id;
? }
? @Override
? public void run() {
? ?System.out.println("线程:" + id + " -> 运行...");
? ?try {
? ? Thread.sleep(5000);
? ?} catch (Exception e) {
? ? e.printStackTrace();
? ?}
? ?System.out.println("线程:" + id + " -> 结束!");
? }
?}
?public static void main(String[] args) {
? new ZhangPhilExecutorService();
?}
}
运行的输出结果:
线程池执行线程id:0
线程池执行线程id:1
线程池执行线程id:2
线程池执行线程id:3
线程:0 -> 运行...
线程池执行线程id:4
线程:1 -> 运行...
线程池执行线程id:5
线程池执行线程id:6
线程池执行线程id:7
线程池执行线程id:8
线程池执行线程id:9
线程:1 -> 结束!
线程:0 -> 结束!
线程:2 -> 运行...
线程:3 -> 运行...
线程:3 -> 结束!
线程:2 -> 结束!
线程:4 -> 运行...
线程:5 -> 运行...
线程:4 -> 结束!
线程:5 -> 结束!
线程:6 -> 运行...
线程:7 -> 运行...
线程:7 -> 结束!
线程:6 -> 结束!
线程:8 -> 运行...
线程:9 -> 运行...
线程:9 -> 结束!
线程:8 -> 结束!