Java multi-threading (4) - thread deadlocks and lock

Deadlock thread

Deadlock

  • Different threads are occupied by other resources required to synchronize not give up, we are waiting for the other to give
    synchronization resources they need to form a thread deadlock
  • After the deadlock, does not appear abnormal, prompt does not appear, but all the threads are in a
    blocked state and can not continue

Example:

public class Thread03 {
    public static void main(String[] args) {
        StringBuffer s1=new StringBuffer();
        StringBuffer s2= new StringBuffer();
        //使用匿名方式来创建对象
        new Thread(){
            public void run(){
                synchronized (s1){
                    s1.append("a");
                    s2.append("1");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (s2){
                        s1.append("b");
                        s2.append("2");

                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();
        //使用实现Runnable接口的形式来实现
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (s2){
                    s1.append("c");
                    s2.append("3");

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (s1){
                        s1.append("d");
                        s2.append("4");

                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }).start();
    }
}

operation result:
Here Insert Picture Description

A deadlock occurs, neither error nor program end

Deadlock reasons: When the thread starts executing a lock s1 happen to get blocked, cpu to execute two threads, and the thread lock s2 also occurred two to get blocked, which is based on the synchronization lock mechanism, not been performed for all synchronization codes , the lock is not released, so a thread needs s2, and two threads need s1, two threads are not free himself occupied lock, so the deadlock.

Solution

  • Specialized algorithms, principles
  • Minimize define the synchronization of resources
  • Try to avoid nested sync

Lock (lock)

class win implements Runnable{
    private int ticket=100;
    private ReentrantLock lock =new ReentrantLock();
    public void run(){
        while (true){
            try {
                //调用lock方法
                lock.lock();
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + ": 售票" + ticket);
                    ticket--;
                } else {
                    break;
                }
            }finally {
                //3.解锁
                lock.unlock();
            }
        }
    }
}
public class Locktest {
    public static void main(String[] args) {
        win w=new win();
        Thread t1=new Thread(w);
        Thread t2=new Thread(w);
        Thread t3=new Thread(w);

        t1.start();
        t2.start();
        t3.start();
    }
}

Lock synchronized with the similarities and differences:

  • The same: both can solve thread safety issues
  • Different: synchronized mechanisms been performed after the corresponding synchronization code, synchronization monitor automatically release
    Lock need to manually start the synchronization (Lock ()), while the end of the synchronization is also achieved manually (UNLOCK ())

Order of precedence:

  • Lock -----> sync block (has entered the body of the method of allocating the corresponding resource) -----> synchronization method (Method outside the body)
Published 45 original articles · won praise 43 · views 7070

Guess you like

Origin blog.csdn.net/qq_42193790/article/details/104440250
Recommended