“This is the 16th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Thread locked

Why is it locked?

There are two threads waiting, and when the lock is opened for thread 1, thread 1 continues to lock the following thread 2, which means that thread 2 does not get out of the lock, so thread 2 cannot enter.

A waiting thread is said to be locked because the conditions needed to wake it up are never established, causing it to never be in a RUNNABLE state.

Although deadlocks and locks appear to be threads waiting, unable to continue to complete the task, but the conditions are different, even in the case of impossible deadlock may also occur, so we can not use the method to deal with deadlocks to solve the problem of locking.

Locking includes signal loss locking and nested monitor locking.

The typical case of signal loss locking is that the waiting thread does not judge the protection Condition before executing object.wait ()/ condition.await (). There may be no other thread to update the variable involved in the corresponding protection Condition to make it valid and notify the thread, so that the thread remains in the wait state.

Solution 1:

Waiting for the approach

The following code:

Public void waitMethod(){synchronized(lock1) {synchronized(lock2){while(condition){lock2.wait(); }} / /... }}Copy the code

Solution 2:

Wake up a thread manually in the main thread

The following code:

Synchronized (s2) {s2.notifyall (); }Copy the code

Solution three:

Synchronized synchronized code blocks are replaced by Semaphore thread synchronization helper classes, whose parameters control the number of threads accessing resources at the same time.

The following code:

import java.util.concurrent.Semaphore;

public class DeadLock { public static void main(String[] args) { Semaphore s1=new Semaphore(1); Semaphore s2=new Semaphore(0); Semaphore s3=new Semaphore(0); New Thread() {public void run() {int count=100; while(count>0) { try { s1.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } count–; System.out.println(count); s2.release(); } } }.start(); New Thread() {public void run() {int count=100; while(count>0) { try { s2.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } count–; System.out.println(count); s3.release(); } } }.start(); New Thread() {public void run() {int count=100; while(count>0) { try { s3.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } count–; System.out.println(count); s1.release(); } } }.start(); }}