Java thread hangs in several ways

       There will certainly be a thread suspended this happens in Java when using threads, provides three ways in Java: suspend / resume, wait / notify, notifyAll, park / unpark.

1.suspend/resume

     This approach has been abandoned in Java, because it is likely to lead to deadlock. When using a keyword such as synchronized

synchronized (this) { 
   Thread.currentThread().suspend();
}

      This time using the resume is to not wake the thread, if there is a situation only call suspend resume method after method, this method also can not suspend the wake of, because this sequence of events has caused deadlock appear.

2.wait/notify,notifyAll

       This is the common thread is suspended in Java methods, when calling thread will wait method of automatically freed possession thread resource lock, and then wait to wake up approach by notify or notifyAll method, so there is no deadlock in this place was as suspend / resume mentioned, if during the wait operation after notify or notifyAll method, then certainly there will be a deadlock.

      Here it must explain that sleep method, although it is also possible to suspend the thread, but it method InterruptedException exception when sleep after a certain time it will be executed automatically back generates, interrupted sleep can also take the initiative to interrupt method by method threading wake.

3.park/unpark

      The park is meant literal meaning of the parking lot, you need to call the park to suspend the thread unpark use to wake up, this is no distinction between the order of, if you advance the unpark, then making park is also possible, but advance a plurality unpark can only be seen as a unpark, can not be repeated overlay, if the park again if needed to unpark a new wake-up operation, the parking operation such as you were in the parking lot, if you make a parking reservation in advance, you before entering the car park are not possible multiple appointments, which all appointments deducted only once money (unpark), but that all appointments operations are seen as proof that once you enter the car park (park), and If you leave a parking once you want to do next by a token payment (unpark), it has been used in the appointment can not be comprehensive and balanced, you can only re-appointment or directly into the parking lot, leaving only pay once again ( unpark).

      Call park / unpark using LockSupport.park () / LockSupport.unpark ().

      That use park / unpark use the synchronized keyword there will be a deadlock situation, because it does not release the lock resource occupied by a thread, so the use of the time also need attention.

Guess you like

Origin www.iteye.com/blog/357029540-2443629