我们大家都知道,在处理多线程服务并发时,由于创建线程需要占用很多的系统资源,所以为了避免这些不必要的损耗,通常我们采用线程池来解决这些问题。
线程池的基本原理是,首先创建并保持一定数量的线程,当需要使用线程时,我们从池中取得线程,再将需要运行的任务交给线程进行处理,当任务完成后再将其释放回池中。
下面,我给出一个很简单的实现模型,仅供参考。
ThreadPool.java
packageorg.loon.framework.util.test;

importjava.util.LinkedList;
importjava.util.List;


/***//**
*<p>
*Title:LoonFramework
*</p>
*<p>
*Description:
*</p>
*<p>
*Copyright:Copyright(c)2007
*</p>
*<p>
*Company:LoonFramework
*</p>
*
*@authorchenpeng
*@email:ceponline@yahoo.com.cn
*@version0.1
*/

publicclassThreadPool...{

privatestaticThreadPoolinstance=null;

//优先级低
publicstaticfinalintPRIORITY_LOW=0;

//普通
publicstaticfinalintPRIORITY_NORMAL=1;

//高
publicstaticfinalintPRIORITY_HIGH=2;

//用以保存空闲连接
privateList[]_idxThreads;

//关闭
privateboolean_shutdown=false;

//线程数量
privateint_threadCount=0;

//debug信息是否输出
privateboolean_debug=false;


/***//**
*返回ThreadPool实例
*
*@return
*/

publicstaticThreadPoolgetInstance()...{

if(instance==null)...{
instance=newThreadPool();
}
returninstance;
}

//初始化线程list

privateThreadPool()...{

this._idxThreads=newList[]...{newLinkedList(),newLinkedList(),
newLinkedList()};
this._threadCount=0;
}


/***//**
*同步方法,完成任务后将资源放回线程池中
*@paramrepool
*/

protectedsynchronizedvoidrepool(Pooledrepool)...{

if(this._shutdown)...{

if(this._debug)...{
System.out.println("ThreadPool.repool():重设中……");
}
//优先级别判定

switch(repool.getPriority())...{
caseThread.MIN_PRIORITY:
this._idxThreads[PRIORITY_LOW].add(repool);
break;
caseThread.NORM_PRIORITY:
this._idxThreads[PRIORITY_NORMAL].add(repool);
break;
caseThread.MAX_PRIORITY:
this._idxThreads[PRIORITY_HIGH].add(repool);
break;
default:
thrownewIllegalStateException("没有此种级别");
}
//通知所有线程
notifyAll();


}else...{

if(this._debug)...{
System.out.println("ThreadPool.repool():注销中……");
}
repool.shutDown();
}

if(this._debug)...{
System.out.println("ThreadPool.repool():完成");
}
}

publicvoidsetDebug(booleandebug)...{
this._debug=debug;
}

publicsynchronizedvoidshutDown()...{
this._shutdown=true;

if(this._debug)...{
System.out.println("ThreadPool.shutDown():关闭中……");
}

for(intindex=0;index<=PRIORITY_NORMAL;index++)...{
Listthreads=this._idxThreads[index];

for(intthreadIndex=0;threadIndex<threads.size();threadIndex++)...{
PooledidleThread=(Pooled)threads.get(threadIndex);
idleThread.shutDown();
}
}
notifyAll();
}


/***//**
*以指定的优先级启动线程
*@paramtarget
*@parampriority
*/

publicsynchronizedvoidstart(Runnabletarget,intpriority)...{
Pooledthread=null;
ListidleList=this._idxThreads[priority];
intidleSize=idleList.size();


if(idleSize>0)...{
intlastIndex=idleSize-1;
thread=(Pooled)idleList.get(lastIndex);
idleList.remove(idleList);
thread.setTarget(target);

}else...{
this._threadCount++;
thread=newPooled(target,"Pooled->"+this._threadCount,this);

switch(priority)...{

casePRIORITY_LOW:
thread.setPriority(Thread.MIN_PRIORITY);
break;
casePRIORITY_NORMAL:
thread.setPriority(Thread.NORM_PRIORITY);
break;
casePRIORITY_HIGH:
thread.setPriority(Thread.MAX_PRIORITY);
break;
default:
thread.setPriority(Thread.NORM_PRIORITY);
}
//启动
thread.start();

}


}


/***//**
*返回线程数量
*
*@return
*/

publicintgetThreadsCount()...{
returnthis._threadCount;
}

}
Pooled.java:
packageorg.loon.framework.util.test;


/***//**
*<p>
*Title:LoonFramework
*</p>
*<p>
*Description:
*</p>
*<p>
*Copyright:Copyright(c)2007
*</p>
*<p>
*Company:LoonFramework
*</p>
*
*@authorchenpeng
*@email:ceponline@yahoo.com.cn
*@version0.1
*/

publicclassPooledextendsThread...{

privateThreadPool_pool;

privateRunnable_target;

privateboolean_shutdown=false;

privateboolean_idle=false;


publicPooled(Runnabletarget)...{
super(target);
}


publicPooled(Runnabletarget,Stringname)...{
super(target,name);
}


publicPooled(Runnabletarget,Stringname,ThreadPoolpool)...{
super(name);
this._pool=pool;
this._target=target;
}


publicPooled(Stringname)...{
super(name);
}


publicPooled(ThreadGroupgroup,Runnabletarget)...{
super(group,target);
}


publicPooled(ThreadGroupgroup,Runnabletarget,Stringname)...{
super(group,target,name);
}


publicPooled(ThreadGroupgroup,Stringname)...{
super(group,name);
}


publicRunnablegetTarget()...{
returnthis._target;
}


publicbooleanisIdle()...{
returnthis._idle;
}


publicvoidrun()...{

while(!this._shutdown)...{
this._idle=false;

if(this._target!=null)...{
this._target.run();
}
this._idle=true;

try...{

this._pool.repool(this);


synchronized(this)...{
wait();
}


}catch(InterruptedExceptionex)...{
System.err.println(ex.getMessage());
}
this._idle=false;
}
}


publicsynchronizedvoidsetTarget(Runnabletarget)...{
this._target=target;
notifyAll();
}


publicsynchronizedvoidshutDown()...{
this._shutdown=true;
notifyAll();
}

}
测试用类:
packageorg.loon.framework.util.test;

/***//**
*<p>Title:LoonFramework</p>
*<p>Description:线程池测试</p>
*<p>Copyright:Copyright(c)2007</p>
*<p>Company:LoonFramework</p>
*@authorchenpeng
*@email:ceponline@yahoo.com.cn
*@version0.1
*/

publicclassThreadPoolTest...{



privatestaticRunnablecreateRunnable(finalintid)...{

returnnewRunnable()...{

publicvoidrun()...{
System.out.println("线程"+id+",运行 ");

try...{
Thread.sleep(1000);
}

catch(InterruptedExceptionex)...{}
System.out.println("线程"+id+",结束");
}
};
}


publicstaticvoidmain(String[]args)...{
ThreadPoolpool=ThreadPool.getInstance();
pool.setDebug(true);

for(inti=1;i<=10;i++)...{
//根据数值,设定不同优先级

if(i%2==0)...{
pool.start(createRunnable(i),ThreadPool.PRIORITY_HIGH);

}else...{
pool.start(createRunnable(i),ThreadPool.PRIORITY_LOW);
}
}
System.out.println("线程池测试中……");
System.out.println("线程池线程总数:"+pool.getThreadsCount());
pool.shutDown();
}
}

分享到:
相关推荐
线程池提交优先级,执行优先级
JAVA多线程,并设置优先级案例,一段完整的程序,加上自己的东西就可以跑起来
理解Java线程池的原理和实现,可以帮助我们更有效地管理并发任务,提升系统性能,同时避免资源浪费和线程安全问题。在实际开发中,合理配置线程池参数,结合业务场景选择合适的线程池类型,是优化系统性能的关键步骤...
Java线程池是一种高效管理并发任务执行的机制,它通过预先创建并维护一定数量的线程,从而避免了频繁地创建和销毁线程所带来的性能开销。在Java中,线程池的实现主要依赖于`java.util.concurrent`包中的`...
总之,Java线程池是实现多线程并行处理的关键工具,理解和熟练使用它可以显著提高程序的并发性能,降低系统的资源消耗。通过深入学习和实践,我们可以更好地利用线程池来优化我们的Java应用程序。
Java线程池是一种高效利用系统资源、管理并发执行任务的机制。...总的来说,理解Java线程池的工作原理和实现对于优化并发应用程序至关重要,它可以帮助我们更好地控制系统的并发度,提高系统的响应速度和资源利用率。
Java线程池是一种高效管理线程的机制,它允许开发者预先设定线程的数量,并通过池化的方式重用已创建的线程,以提高系统性能,减少线程的创建和销毁开销。线程池在Java中是通过`java.util.concurrent`包下的`...
Java线程池是Java并发编程中的重要组成部分,它在多线程和高并发场景下扮演着关键角色。本文将深入探讨Java线程池的源码分析,并对比不同类型的线程池,以帮助开发者更好地理解和利用这一强大的工具。 首先,我们要...
Java线程池是一种高效管理线程资源的工具,它通过维护一组可重用的线程来减少创建和销毁线程的开销。在Java中,`java.util.concurrent`包提供了`ExecutorService`接口和它的实现类,如`ThreadPoolExecutor`,来支持...
Java线程池是一种高效管理线程资源的技术,它允许开发者创建一组可重用的工作线程,从而避免频繁地创建和销毁线程带来的性能开销。线程池在Java中主要通过`java.util.concurrent`包中的`ExecutorService`接口及其...
JVM优先级线程池做任务队列的实现方法是指在Java虚拟机(JVM)中使用线程池来管理和执行任务队列的方法。这种方法可以将任务按照优先级排队,并且可以根据实际情况动态调整线程池的大小,从而提高系统的并发处理能力...
### Java线程池详解 #### 一、线程与线程池的概念 在Java中,线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位。一个进程(例如某个Java应用)至少有一个线程,如果线程...
Java线程池是Java并发编程中的重要组成部分,它在多线程编程中扮演着至关重要的角色,有效地管理和调度了大量的并发任务。线程池通过预先创建并维护一组可重用线程,来提升程序的性能和效率,避免了频繁地创建和销毁...
Java线程池实现批量下载文件 Java线程池实现批量下载文件是指使用Java语言和线程池机制来实现批量下载文件的功能。这种方法可以大幅提高下载速度和效率,特别是当需要下载大量文件时。下面将对Java线程池实现批量...
所有的可以显示出来的图形元素都称为Component,Component代表了所有的可见的图形元素,... Pannel应用比较典型的就是Applet(JAVA的页面小应用程序),现在基本上已经不用了,AJAX和JAVASCRIPT完全取代了它的应用。
`ThreadPoolExecutor`是Java线程池的核心实现类,它的构造函数接受多个参数,用于定制线程池的行为: 1. corePoolSize:核心线程数,线程池会尽量保持这个数量的线程活跃,即使它们空闲。 2. maximumPoolSize:最大...
Java线程池是一种高效管理线程的工具,它允许开发者预先创建一组线程,并复用它们来处理任务,从而降低了创建和销毁线程的开销。线程池的使用尤其适用于处理大量短小任务的场景,例如Web服务器、数据库服务器等。在...
Java线程池是一种高效管理线程的技术,它允许开发者预创建一组线程,而不是每当有新任务时就创建一个新的线程。线程池的使用在处理大量短小任务时尤其有益,因为它减少了线程创建和销毁的开销,避免了因过多线程导致...