Java一个简单的线程池实现
线程池代码
import java.util.List;
import java.util.Vector;
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_;
}
//将线程repoolingThread从新放回到池中,这个方式是同步方法。
//这个方法会在多线程的环境中调用,设计这个方法的目的是让工作者线程
//在执行完target中的任务后,调用池类的repool()方法,
//将线程自身从新放回到池中。只所以这么做是因为线程池并不能预见到
//工作者线程何时会完成任务。参考PooledThread的相关代码。
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,并唤醒它
//从空闲的线程队列中获取
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();
}
}
}
工作者线程代码:
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()。
//这就使线程池实现的要点。
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 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();
}
}
结果
Testing ThreadPool 
Creating ThreadPool 
Starting a new thread 
Testrunner sleeping 5 seconds 
count : 0
Thread count : 1
ThreadPool : shutting down 
ThreadPool : shutdown done.
Testrunner leaving 
ThreadPool.repool() : Destroying incoming thread
.
ThreadPool.recycle() : done.
Java一个简单的线程池实现的更多相关文章
- linux网络编程-一个简单的线程池(41)
有时我们会需要大量线程来处理一些相互独立的任务,为了避免频繁的申请释放线程所带来的开销,我们可以使用线程池 1.线程池拥有若干个线程,是线程的集合,线程池中的线程数目有严格的要求,用于执行大量的相对短 ...
- Linux C 一个简单的线程池程序设计
最近在学习linux下的编程,刚开始接触感觉有点复杂,今天把线程里比较重要的线程池程序重新理解梳理一下. 实现功能:创建一个线程池,该线程池包含若干个线程,以及一个任务队列,当有新的任务出现时,如果任 ...
- Linux C 实现一个简单的线程池
线程池的定义 线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线程池线程都是后台线程.每个线程都使用默认的堆栈大小,以默认的优先级运行,并处于多线程单元中.如 ...
- Java多线程系列--“JUC线程池”03之 线程池原理(二)
概要 在前面一章"Java多线程系列--“JUC线程池”02之 线程池原理(一)"中介绍了线程池的数据结构,本章会通过分析线程池的源码,对线程池进行说明.内容包括:线程池示例参考代 ...
- Java多线程系列 JUC线程池01 线程池框架
转载 http://www.cnblogs.com/skywang12345/p/3509903.html 为什么引入Executor线程池框架 new Thread()的缺点 1. 每次new T ...
- 【C/C++开发】C++实现简单的线程池
C++实现简单的线程池 线程池编程简介: 在我们的服务端的程序中运用了大量关于池的概念,线程池.连接池.内存池.对象池等等.使用池的概念后可以高效利用服务器端的资源,比如没有大量的线程在系统中进行上下 ...
- Java网络与多线程系列之1:实现一个简单的对象池
前言 为什么要从对象池开始呢,先从一个网络IO操作的demo说起 比如下面这段代码,显而易见已经在代码中使用了一个固定大小的线程池,所以现在的重点在实现Runnble接口的匿名对象上,这个对象每次创建 ...
- java之并发编程线程池的学习
如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间. java.uitl.concurrent.Thre ...
- Java并发编程:线程池的使用
Java并发编程:线程池的使用 在前面的文章中,我们使用线程的时候就去创建一个线程,这样实现起来非常简便,但是就会有一个问题: 如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了, ...
随机推荐
- python ros topic demo
发布者: #!/usr/bin/env python #coding=utf- import rospy from std_msgs.msg import String def talker(): ...
- MongoDB(课时28 group操作)
3.7.3 group操作 使用“group”操作可以实现数据的分组操作,MongoDB里将集合依据不同的的key进行分组操作,并且每个组产生一个处理文档. 范例:查询年龄大于等于19岁的学生信息,并 ...
- [原][OSG]整理osg渲染一帧的流程
参考:最长的一帧 先看下frame void ViewerBase::frame(double simulationTime) { advance(simulationTime);//记录仿真时间,帧 ...
- img srcset 和 sizes
img srcset 和 sizes 诞生的目的是解决图片清晰度和节省加载图片大小问题,比方说我需要在retina高的硬件上看到更细腻的图片,又或者我要在电脑看到的图片和在手机上的图片不一样. 解 ...
- Lua面向对象 --- 继承
工程结构: BasePlayer.lua: BasePlayer = {} BasePlayer.root = "BasePlayer" function BasePlayer:S ...
- 在浏览器外打开PDF文档
One function you might find annoying with PDFs and PDF Readers is that when you click on a link to a ...
- Lightoj Halloween Costumes
题意:给出要n个时间穿的服装.服装脱下就不能再穿.问最少要准备多少? dp[i][j]表示i到j之间最少花费.如果n=1(n指长度),肯定结果为1,n=2时,也很好算.然后n=3的时候dp[i][j] ...
- Android之ToolBar和自定义ToolBar实现沉浸式状态栏
沉浸式状态栏确切的说应该叫做透明状态栏.一般情况下,状态栏的底色都为黑色,而沉浸式状态栏则是把状态栏设置为透明或者半透明. 沉浸式状态栏是从android Kitkat(Android 4.4)开始出 ...
- mac连接Windows远程桌面
先打开微软官方的下载面面:http://www.microsoft.com/zh-CN/download/details.aspx?id=18140 下载远程连接客户端 http://jingyan. ...
- OAF开发中一些LOV相关技巧 (转)
原文地址:OAF开发中一些LOV相关技巧 在OAF开发中,LOV的使用频率是很高的,它由两部分构成一是页面上的LOV输入框(如OAMESSageLovInputBean),二是弹出的LOV模式窗口(O ...