jdk5的线程池

接上篇 [url]http://www.iteye.com/post/339894[/url] 继续讨论线程池
jdk5也提供了线程池 而且非常简单

[code]ExecutorService pool = Executors.newFixedThreadPool(4); //创建线程池 4个工作线程
pool.execute(new RunnableTask()); //向任务队列添加任务,任务是一个Runnbale的实现类
pool.shutdown();//停止工作线程[/code]
看一下 这两句
[code]pool.execute(new RunnableTask()) //RunnableTask implements Runnable
//这句是在上篇文章中
pool.addTask(new SimpleTask(new MyManager(), i)) //SimpleTask implements Task [/code]
看出什么不同了吗? [color=blue]jdk5实现的是Runnble接口 也就是说它的每个任务又是一个线程?是这样吗? 不是[/color]
让我们看看是怎么实现的吧
[code]/**
* Run a single task between before/after methods.
*/
private void runTask(Runnable task) {
final ReentrantLock runLock = this.runLock;
runLock.lock();
try {
// Abort now if immediate cancel. Otherwise, we have
// committed to run this task.
if (runState == STOP)
return;

Thread.interrupted(); // clear interrupt status on entry
boolean ran = false;
beforeExecute(thread, task);
try {
task.run(); //调用的是run()方法 而不是start()
ran = true;
afterExecute(task, null);
++completedTasks;
} catch(RuntimeException ex) {
if (!ran)
afterExecute(task, ex);
// Else the exception occurred within
// afterExecute itself in which case we don't
// want to call it again.
throw ex;
}
} finally {
runLock.unlock();
}
}[/code]
请注意task.run(); 这句, 这儿并没有启动线程 而是简单的调用了一个普通对象的一个方法
runTask方法是在工作线程(Worker)中调用的
[code]
/**
* Worker threads
*/
private class Worker implements Runnable {
//只列出run方法 其他省略
public void run() {
try {
Runnable task = firstTask;
firstTask = null;
while (task != null || (task = getTask()) != null) {
runTask(task); //执行任务
task = null; // unnecessary but can help GC
}
} catch(InterruptedException ie) {
// fall through
} finally {
workerDone(this);
}
}
}[/code]

jdk5的开发人员也真够省的,多创建一个任务接口多好理解啊, 非要用Runnable接口 误导我们。
以上的代码片段都节选自jdk5中ThreadPoolExecutor
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值