首页 技术 正文
技术 2022年11月15日
0 收藏 658 点赞 3,194 浏览 6469 个字

线程池简介

  多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。

  假设一个服务器完成一项任务所需时间为:

  1. T1 创建线程时间
  2. T2 在线程中执行任务的时间
  3. T3 销毁线程时间

  如果:T1 + T3 远大于 T2,则可以采用线程池,以提高服务器性能。

  一个线程池包括以下四个基本组成部分:

  1. 线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
  2. 工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
  3. 任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
  4. 任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。

  线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。

  它把T1,T3分别安排在服务器程序的启动和结束的时间段或者一些空闲的时间段,这样在服务器程序处理客户请求时,不会有T1,T3的开销了。

  线程池不仅调整T1,T3产生的时间段,而且它还显著减少了创建线程的数目,看一个例子:

  假设一个服务器一天要处理50000个请求,并且每个请求需要一个单独的线程完成。在线程池中,线程数一般是固定的,所以产生线程总数不会超过线程池中线程的数目,而如果服务器不利用线程池来处理这些请求则线程总数为50000。一般线程池大小是远小于50000。所以利用线程池的服务器程序不会为了创建50000而在处理请求时浪费时间,从而提高效率。

代码实现中并没有实现任务接口,而是把Runnable对象加入到线程池管理器(ThreadPool),把剩下的事情交由线程池管理器(ThreadPool)来完成

用Java实现简单的线程池  

  线程池实现

 import java.util.List;
import java.util.Vector; /**
*
* @description:线程池
* @author liuchengwei(wwwlllll@126.com)
* @date Sep 19, 2014 10:15:32 PM
*/
public class ThreadPool {
private static ThreadPool instance_ = null;
//定义优先级别常数,空闲的线程按照优先级不同分别存放在三个vector中
public static final int LOW_PRIORITY = 0;
public static final int NORMAL_PRIORITY = 1;
public static final int HIGH_PRIORITY = 2;
//保存空闲线程的List,或者说它是"池"
private List<PooledThread>[] idleThreads_;
private boolean shutDown_ = false;
private int threadCreationCounter_; //以创建的线程的个数
private boolean debug_ = false; //是否输出调试信息 //构造函数,因为这个类视作为singleton实现的,因此构造函数为私有
private ThreadPool() {
// 产生空闲线程.三个vector分别存放分别处在三个优先级的线程的引用
List[] idleThreads = { new Vector(5), new Vector(5), new Vector(5) };
idleThreads_ = idleThreads;
threadCreationCounter_ = 0;
} public int getCreatedThreadsCount() {
return threadCreationCounter_;
} //通过这个函数得到线程池类的实例
public static ThreadPool instance() {
if (instance_ == null)
instance_ = new ThreadPool();
return instance_;
} public boolean isDebug() {
return debug_;
} /**
*
* @description:
* 将线程repoolingThread从新放回到池中,这个方式是同步方法。
* 这个方法会在多线程的环境中调用,设计这个方法的目的是让工作者线程
* 在执行完target中的任务后,调用池类的repool()方法,
* 将线程自身从新放回到池中。只所以这么做是因为线程池并不能预见到
* 工作者线程何时会完成任务。
* @author liuchengwei(wwwlllll@126.com)
* @date Sep 19, 2014 10:15:59 PM
*/
protected synchronized void repool(PooledThread repoolingThread) {
if (!shutDown_) {
if (debug_) {
System.out.println("ThreadPool.repool() : repooling ");
}
switch (repoolingThread.getPriority()) {
case Thread.MIN_PRIORITY: {
idleThreads_[LOW_PRIORITY].add(repoolingThread);
break;
}
case Thread.NORM_PRIORITY: {
idleThreads_[NORMAL_PRIORITY].add(repoolingThread);
break;
}
case Thread.MAX_PRIORITY: {
idleThreads_[HIGH_PRIORITY].add(repoolingThread);
break;
}
default:
throw new IllegalStateException("Illegal priority found while repooling a Thread!");
}
notifyAll();//通知所有的线程
}
else {
if (debug_) {
System.out.println("ThreadPool.repool() : Destroying incoming thread.");
}
repoolingThread.shutDown();//关闭线程
}
if (debug_) {
System.out.println("ThreadPool.recycle() : done.");
}
} public void setDebug(boolean newDebug) {
debug_ = newDebug;
} //停止池中所有线程
public synchronized void shutdown() {
shutDown_ = true;
if (debug_) {
System.out.println("ThreadPool : shutting down ");
}
for (int prioIndex = 0; prioIndex <= HIGH_PRIORITY; prioIndex++) {
List prioThreads = idleThreads_[prioIndex];
for (int threadIndex = 0; threadIndex < prioThreads.size(); threadIndex++) {
PooledThread idleThread = (PooledThread) prioThreads.get(threadIndex);
idleThread.shutDown();
}
}
notifyAll();
if (debug_) {
System.out.println("ThreadPool : shutdown done.");
}
} //以Runnable为target,从池中选择一个优先级为priority的线程创建线程并让线程运行。
public synchronized void start(Runnable target, int priority) {
PooledThread thread = null; //被选出来执行target的线程
List idleList = idleThreads_[priority];
if (idleList.size() > 0) {
/**
* 如果池中相应优先级的线程有空闲的,那么从中取出一个
* 设置它的target,并唤醒它
* 从空闲的线程队列中获取
*
* @author liuchengwei(wwwlllll@126.com)
*/
int lastIndex = idleList.size() - 1;
thread = (PooledThread) idleList.get(lastIndex);
idleList.remove(lastIndex);
thread.setTarget(target);
}
//池中没有相应优先级的线程
else {
threadCreationCounter_++;
// 创建新线程,
thread = new PooledThread(target, "PooledThread #" + threadCreationCounter_, this);
// 新线程放入池中
switch (priority) {
case LOW_PRIORITY: {
thread.setPriority(Thread.MIN_PRIORITY);
break;
}
case NORMAL_PRIORITY: {
thread.setPriority(Thread.NORM_PRIORITY);
break;
}
case HIGH_PRIORITY: {
thread.setPriority(Thread.MAX_PRIORITY);
break;
}
default: {
thread.setPriority(Thread.NORM_PRIORITY);
break;
}
}
//启动这个线程
thread.start();
}
}
}

  工作者线程实现

 /**
*
* @description:线程
* @author liuchengwei(wwwlllll@126.com)
* @date Sep 19, 2014 9:39:34 PM
*/
public class PooledThread extends Thread {
private ThreadPool pool_; // 池中线程需要知道自己所在的池
private Runnable target_; // 线程的任务
private boolean shutDown_ = false;
private boolean idle_ = false;//设置是否让线程处于等待状态 private PooledThread() {
super();
} private PooledThread(Runnable target) {
super(target); //初始化父类
} private PooledThread(Runnable target, String name) {
super(target, name);
} public PooledThread(Runnable target, String name, ThreadPool pool) {
super(name);
pool_ = pool;
target_ = target;
} private PooledThread(String name) {
super(name);//初始化父类
} private PooledThread(ThreadGroup group, Runnable target) {
super(group, target);
} private PooledThread(ThreadGroup group, Runnable target, String name) {
super(group, target, name);
} private PooledThread(ThreadGroup group, String name) {
super(group, name);
} public java.lang.Runnable getTarget() {
return target_;
} public boolean isIdle() {
return idle_;//返回当前的状态
} /**
* 工作者线程与通常线程不同之处在于run()方法的不同。通常的线程,
* 完成线程应该执行的代码后,自然退出,线程结束。
* 虚拟机在线程结束后收回分配给线程的资源,线程对象被垃圾回收。
* 而这在池化的工作者线程中是应该避免的,否则线程池就失去了意义。
* 作为可以被放入池中并重新利用的工作者线程,它的run()方法不应该结束,
* 随意,在随后可以看到的实现中,run()方法执行完target对象的代码后,
* 就将自身repool(),然后调用wait()方法,使自己睡眠而不是退出循环和run()。
* 这就使线程池实现的要点。
*
* @author liuchengwei(wwwlllll@126.com)
*/
public void run() {
// 这个循环不能结束,除非池类要求线程结束
// 每一次循环都会执行一次池类分配给的任务target
while (!shutDown_) {
idle_ = false;
if (target_ != null) {
target_.run(); // 运行target中的代码
}
idle_ = true;
try {
//线程通知池重新将自己放回到池中
pool_.repool(this); //
//进入池中后睡眠,等待被唤醒执行新的任务,
//这里是线程池中线程于普通线程的run()不同的地方。
synchronized (this) {
wait();
}
}
catch (InterruptedException ie) {
}
idle_ = false;
}
//循环这里不能结束,否则线程结束,资源被VM收回,
//就无法起到线程池的作用了
} public synchronized void setTarget(java.lang.Runnable newTarget) {//设置新的target,并唤醒睡眠中的线程
target_ = newTarget; // 新任务
notifyAll(); // 唤醒睡眠的线程
} public synchronized void shutDown() {
shutDown_ = true;
notifyAll();
}
}

  测试代码

 public class Test {
public static void main(String[] args) {
System.out.println("Testing ThreadPool ");
System.out.println("Creating ThreadPool ");
ThreadPool pool = ThreadPool.instance();
pool.setDebug(true);
class TestRunner implements Runnable {
public int count = 0; public void run() {
System.out.println("Testrunner sleeping 5 seconds ");
//此方法使本线程睡眠5秒
synchronized (this) {
try {
wait(5000);//等待5秒时间
}
catch (InterruptedException ioe) {
}
}
System.out.println("Testrunner leaving ");
count++;
}
}
System.out.println("Starting a new thread ");
TestRunner runner = new TestRunner();
pool.start(runner, pool.HIGH_PRIORITY);
System.out.println("count : " + runner.count);
System.out.println("Thread count : " + pool.getCreatedThreadsCount());
pool.shutdown();
} }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295