博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线程池 Thread Pools
阅读量:4070 次
发布时间:2019-05-25

本文共 2898 字,大约阅读时间需要 9 分钟。

线程池

原文地址:  作者: Jakob Jenkov  译者:  校对:方腾飞

线程池(Thread Pool)对于限制应用程序中同一时刻运行的线程数很有用。因为每启动一个新线程都会有相应的性能开销,每个线程都需要给栈分配一些内存等等。

我们可以把并发执行的任务传递给一个线程池,来替代为每个并发执行的任务都启动一个新的线程。只要池里有空闲的线程,任务就会分配给一个线程执行。在线程池的内部,任务被插入一个阻塞队列( ),线程池里的线程会去取这个队列里的任务。当一个新任务插入队列时,一个空闲线程就会成功的从队列中取出任务并且执行它。

线程池经常应用在多线程服务器上。每个通过网络到达服务器的连接都被包装成一个任务并且传递给线程池。线程池的线程会并发的处理连接上的请求。以后会再深入有关 Java 实现多线程服务器的细节。

Java 5 在 java.util.concurrent 包中自带了内置的线程池,所以你不用非得实现自己的线程池。你可以阅读我写的  的文章以了解更多有关内置线程池的知识。不过无论如何,知道一点关于线程池实现的知识总是有用的。

这里有一个简单的线程池实现:

01 public class ThreadPool {
02  
03   privateBlockingQueue taskQueue =null;
04   privateList<PoolThread> threads =newArrayList<PoolThread>();
05   privatebooleanisStopped = false;
06  
07   publicThreadPool(intnoOfThreads, intmaxNoOfTasks) {
08     taskQueue =newBlockingQueue(maxNoOfTasks);
09  
10     for(inti=0; i<noOfThreads; i++) {
11       threads.add(newPoolThread(taskQueue));
12     }
13     for(PoolThread thread : threads) {
14       thread.start();
15     }
16   }
17  
18   publicvoidsynchronizedexecute(Runnable task) {
19     if(this.isStopped)throw
20       newIllegalStateException("ThreadPool is stopped");
21  
22     this.taskQueue.enqueue(task);
23   }
24  
25   publicsynchronizedbooleanstop() {
26     this.isStopped =true;
27     for(PoolThread thread : threads) {
28       thread.stop();
29     }
30   }
31  
32 }

(校注:原文有编译错误,我修改了下)

01 public class PoolThread extendsThread {
02  
03   privateBlockingQueue<Runnable> taskQueue =null;
04   privateboolean      isStopped =false;
05  
06   publicPoolThread(BlockingQueue<Runnable> queue) {
07     taskQueue = queue;
08   }
09  
10   publicvoidrun() {
11     while(!isStopped()) {
12       try{
13         Runnable runnable =taskQueue.take();
14         runnable.run();
15       } catch(Exception e) {
16         // 写日志或者报告异常,
17         // 但保持线程池运行.
18       }
19     }
20   }
21  
22   publicsynchronizedvoid Stop() {
23     isStopped =true;
24     this.interrupt();// 打断池中线程的 dequeue() 调用.
25   }
26  
27   publicsynchronizedbooleanisStopped() {
28     returnisStopped;
29   }
30 }

线程池的实现由两部分组成。类 ThreadPool 是线程池的公开接口,而类 PoolThread 用来实现执行任务的子线程。

为了执行一个任务,方法 ThreadPool.execute(Runnable r) 用 Runnable 的实现作为调用参数,Runnable对象模拟任务。在内部,Runnable 对象被放入 阻塞队列 (Blocking Queue),等待着被子线程取出队列。

一个空闲的 PoolThread 线程(模拟工作线程)会把 Runnable 对象(任务)从队列中取出并执行。你可以在 PoolThread.run() 方法里看到这些代码(即工作线程从阻塞队列中取出一个任务)。执行完毕后,PoolThread 进入循环并且尝试从队列中再取出一个任务,直到线程终止。

调用 ThreadPool.stop() 方法可以停止 ThreadPool。在内部,调用 stop 先会标记 isStopped 成员变量(为 true)。然后,线程池的每一个子线程都调用 PoolThread.stop() 方法停止运行。注意,如果线程池的 execute() 在 stop() 之后调用,execute() 方法会抛出 IllegalStateException 异常。

 

The threads will stop  after finishing any task they are currently executing.    Notice the    this.interrupt() call inPoolThread.stop(). This makes sure that    a thread blocked in await() call inside thetaskQueue.dequeue()    call breaks out of thewait() call, and leaves thedequeue() method    call with anInterruptedException thrown. This exception is caught in the    PoolThread.run() method, reported, and then the isStopped variable    is checked. SinceisStopped is now true, thePoolThread.run() will    exit and the thread dies.

转载地址:http://cgmji.baihongyu.com/

你可能感兴趣的文章
OS + Linux Disk disk lvm / disk partition / disk mount / disk io
查看>>
RedHat + OS CPU、MEM、DISK
查看>>
net TCP/IP / TIME_WAIT / tcpip / iperf / cain
查看>>
script webshell jspWebShell / pythonWebShell / phpWebShell
查看>>
project site_dns
查看>>
webServer kzserver/1.0.0
查看>>
hd printer lexmark / dazifuyin / dayin / fuyin
查看>>
OS + Unix IBM Aix basic / topas / nmon / filemon / vmstat / iostat / sysstat/sar
查看>>
monitorServer nagios / cacti / tivoli / zabbix / SaltStack
查看>>
my ReadMap subway / metro / map / ditie / gaotie / traffic / jiaotong
查看>>
OS + Linux DNS Server Bind
查看>>
web test flow
查看>>
web test LoadRunner SAP / java / Java Vuser / web_set_max_html_param_len
查看>>
OS + UNIX AIX command
查看>>
OS + UNIX AIX performance
查看>>
OS + UNIX AIX Tools
查看>>
my ReadBook_liutongjingjixue / circulation economics
查看>>
my ReadBook_wangluoyingxiaoyucehua / network marketing / wangluoyingxiao
查看>>
db base database
查看>>
监控服务器端口,Down掉会自动重启,并发送邮件 Linux Shell
查看>>