java concurrent programming notes eight

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, condand mutexdraw 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
        Here Insert Picture Description
  1. The current thread calls Unsafe.park () method
  2. Check _counter, this situation is 0, this time, to obtain _mutex mutex
  3. Thread into the blocked condition variable _cond
  4. Provided _counter = 0
    Here Insert Picture Description
  5. Call Unsafe.unpark (Thread_0) method, set _counter 1
  6. Wake _cond condition variable Thread_0
  7. Thread_0 resume operation
  8. _Counter set to 0
Published 93 original articles · won praise 31 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_43866567/article/details/104976328