相信很多人都想有这样一个线程池,就是没有任务时总有一个线程在运行,任务多时多开线程,少时自动减少线程,程序员不需要去管它,还能让它马上死或者执行完任务再支死,好了,今天我就写这样一个线程池!
看了java的并发包,着实头都大了,看Android源码都没有这么费劲,这里面的这样那样的E文,相信英国人也看不懂吧?真怀疑这是不是意大利人写的!
于是想,我自己根据需要写一个试试,说不定回过头来看看会明白?于是我开始动手---------
写完了一看,不到100行!
这能行吗?自己都不相信,试试!
几次测试都不错,除了一些没有注意到的问题很快就在测试中修复了!
我的测试结果还是相当满意的:
这个类的最大特点是:自动根据任务量来增加销毁线程,只需要一个设定参数即可达到你的需求,而且会平衡创建线程性能消耗与多任务执行慢之间的矛盾;这里简单贴出代码,欢迎测试和提出BUG,过段时间我会贴到github上;
public class SmartThreadPool extends Thread{
private LinkedBlockingQueue<Runnable> queue;
private Runnable contr,smart;
private boolean quit;
private AtomicInteger number;
public SmartThreadPool() {
this(10);
}
public SmartThreadPool(int num) {
queue = new LinkedBlockingQueue<Runnable>();
smart = new SmartRunnable();
contr = new ControlRunnable();
number = new AtomicInteger(num);
}
public void post(Runnable r) {
try {
queue.offer(r, 1000,TimeUnit.MILLISECONDS);
if(Thread.activeCount()<queue.size()/number.get()){
new Thread(smart).start();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public boolean shoutDown(){
return quit = true;
}
public boolean shoutDownNow(){
queue.clear();
return quit = true;
}
@Override
public void run() {
new Thread(contr).start();
}
public class SmartRunnable implements Runnable{
public void run() {
Runnable r = null;
try {
while((r = queue.poll(1000,TimeUnit.MILLISECONDS))!= null ){
r.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class ControlRunnable implements Runnable{
public void run() {
while(!quit){
try {
queue.take().run();
} catch (InterruptedException e) {
e.printStackTrace();
}
// if(Thread.activeCount()<queue.size()/number){
// new Thread(worker).start();
// }
}
}
}
}
这个原理 其实非常简单,相信同学们一看就会明白。