Park & Unpark
Basic use
They class method LockSupport
// 暂停当前线程
LockSupport.park();
// 恢复某个线程的运行
LockSupport.unpark(暂停线程对象)
Feature
Compared with the wait & notify Object
- wait, notify and notifyAll must be used in conjunction with the Object Monitor, and park, unpark do not have to
- park & unpark thread is blocked in units of [] and [] wake up the thread, and notify only a random wake up waiting threads, notifyAll wakes up all waiting threads are, not so precise []
- park & unpark can first unpark, and not to wait & notify notify
park unpark principle
Each thread has its own a Parker object consists of three parts counter
, cond
and mutex
draw an analogy
- Thread like a traveler, Parker like his carry-on bag, backpack tent like condition variable ratio. _counter like backpack alternate dry food (0 depletion, sufficient 1)
- Call the park it is to see or need to stop and rest
- If the spare rations depleted, then got into the tent to rest
- If sufficient spare dry food, so do not need to stop and move on
- Call unpark, like so dry food sufficient
- If you then still thread tent, so that he would wake up and move on
- If the thread is still running at this time, then the next time he calls the park, only dry food is consumed spare, without staying to move on
- Because of the limited bag space, multiple calls to unpark only would add a spare dry food
- Because of the limited bag space, multiple calls to unpark only would add a spare dry food
- The current thread calls Unsafe.park () method
- Check _counter, this situation is 0, this time, to obtain _mutex mutex
- Thread into the blocked condition variable _cond
- Provided _counter = 0
- Call Unsafe.unpark (Thread_0) method, set _counter 1
- Wake _cond condition variable Thread_0
- Thread_0 resume operation
- _Counter set to 0