初识java线程池
来源:互联网 发布:怎么检测网络是否正常 编辑:程序博客网 时间:2024/05/17 18:02
虽然没有并发经验,但是一直挺好奇线程池的实现的:
它怎么能保证线程不死,持续执行呢?
一个线程可以执行N个任务,任务是什么?
于是,看了看ThreadPooledExecutor的实现,哦,原来是Thread,Worker都是实现了Runnable接口的。
线程池包含 一个任务队列,一个工作线程集合
如ThreadPooledExecutor中
/**
* The queue used for holding tasks and handing off to worker
* threads. We do not require that workQueue.poll() returning
* null necessarily means that workQueue.isEmpty(), so rely
* solely on isEmpty to see if the queue is empty (which we must
* do for example when deciding whether to transition from
* SHUTDOWN to TIDYING). This accommodates special-purpose
* queues such as DelayQueues for which poll() is allowed to
* return null even if it may later return non-null when delays
* expire.
*/
private final BlockingQueue<Runnable> workQueue;
/**
* Set containing all worker threads in pool. Accessed only when
* holding mainLock.
*/
private final HashSet<Worker> workers = new HashSet<Worker>();
那么就不难想到,一组线程从一个任务队列中拿任务去执行。
那么就从线程执行任务的代码去找是不是这样的呢
ThreadPooledExecutor的execute()方法中只有addWorker(XX)方法多一点,没有期望出现的run()方法啊,
但是却出现一个
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
...
t.start();
workerStarted = true;
很可能任务的执行在worker中,查看代码
worker是实现了Runnable接口的,看到 public void run() {runWorker(this);}
那么找到了,继续跟踪
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
果然,那么如我们所想,线程从队列中拿任务。那么如果没有任务呢,那不线程就停止了?看getTask()的实现就知道了
/**
* Performs blocking or timed wait for a task, depending on
* current configuration settings, or returns null if this worker
* must exit because of any of:
* 1. There are more than maximumPoolSize workers (due to
* a call to setMaximumPoolSize).
* 2. The pool is stopped.
* 3. The pool is shutdown and the queue is empty.
* 4. This worker timed out waiting for a task, and timed-out
* workers are subject to termination (that is,
* {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
* both before and after the timed wait, and if the queue is
* non-empty, this worker is not the last thread in the pool.
*
* @return task, or null if the worker must exit, in which case
* workerCount is decremented
*/
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
原来是在无限循环里轮询任务啊,那么这么说,这个是阻塞的。有任务就返回,没任务就一直阻塞等待(不同线程池的实现不同)。
看到这里,大致应该也了解了,这就是线程池的思路嘛。
0 0
- 初识 Java 线程池
- 初识 Java 线程池
- java线程池初识
- 初识java线程池
- 初识java线程池
- 初识Java线程池
- 初识java线程
- 初识java线程
- Java线程(初识)
- Java 线程的初识
- java线程浅析[初识线程]
- java线程池(1)初识线程池
- Java多线程编程--初识线程
- java--线程初识(1)
- ThreadPoolExcutor(线程池)初识
- ThreadPoolExcutor(线程池)初识
- Java多线程编程--(1)初识线程
- 初识Java--线程同步(2)
- iosiOS开发之UITableView分割线不顶左解决方法
- SQL温故而知新-基础篇
- jmeter Variables
- C++堆内存,栈内存,new,不new之间的关系梳理
- How install Skype on ubuntu 14.04 ?
- 初识java线程池
- cocos2D文档的使用 2
- PHP获取当前文件路径信息的方法
- 设计模式C++实现(3)——适配器模式
- Android用surface直接显示yuv数据
- 第八章 8-2 数字时钟
- CodeForces 632 C.The Smallest String Concatenation(水~)
- 设计模式C++实现(4)——单例模式
- 大数据生态