线程池(POOL)
池的本质,就是一种“缓存”技术。
是否要缓存一个对象,取决于该对象的创建成本。当然也要考虑刀系统内存大小。
缓存的本质:牺牲时间换取时间。
线程对象的创建成本,比较大。虽然创建线程的成本,比闯进进程的成本要小得多。但是相对比普通得JAVA对象,Thread得创卷成本要高得多。
为了解决这个问题,我们用线程池。
JDK 1.5提供了良好的线程池支持。
Executors - 创建线程池,线程工厂的工具类
- newCachedThreadPool() 创建一个具有缓存功能的线程池,系统根据需要创建线程,这些线程将会被缓存再线程池中
-newFixedThreadPool(int nThreads) 创建创建一个可重用的,具有固定线程数的线程
-newSingleThreadExecutor()创建一个只有单线程的线程池,向当于newFixedThreadPool(1)
-newScheduledThreadPool(int corePoolSize)可以在质地昂延迟后执行县城任务,corePoolSize代表池中所保存的线程 数,也就是线程是空间的也被被奥存在线程池内。
-newSingleThreadScheduledExecutor()
前三个返回一个ExecutorService对象,可执行Runnable和Callable对象,后两个法诺ScheduledExecutorServiec他是ExecutorService的子类。
ExecutorService- 他就是线程池。
Usage Examples
Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool(int) factory method:
class NetworkService implements Runnable {
private final ServerSocket serverSocket;
private final ExecutorService pool;
public NetworkService(int port, int poolSize)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);
}
public void run() { // run the service
try {
for (;;) {
pool.execute(new Handler(serverSocket.accept()));
}
} catch (IOException ex) {
pool.shutdown();
}
}
}
class Handler implements Runnable {
private final Socket socket;
Handler(Socket socket) { this.socket = socket; }
public void run() {
// read and service request on socket
}
}
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().
ScheduledExecutorService- 他就是ExecutorService 的自借口
它可以周期性地调度任务。
线程池编程步骤:
1、通过Executor的静态工厂方法创建ExecutorService或者ScheduledExecutorService对象。
2、调用ExecutorService的方法调教线程submit()
3、调用线程池的shutdown()关闭线程池。