Multithreading-thread unsafe and thread deadlock, synchronization lock Synchronize

Thread insecurity and thread deadlock, synchronization lock Synchronize

What is thread insecurity?

When multiple threads share the same resource, performing read and write operations on the shared resource without using synchronization locks will result in abnormal program execution results and produce abnormal result data. For example: two people grab a ticket. When the last one is strong, both people see a ticket in their eyes, so they both go to grab the ticket at the same time. As a result, both people grabbed the ticket, and the number of tickets becomes 1.

The solution to thread insecurity?

The solution to thread insecurity is to lock the thread and use the thread synchronization mechanism to synchronize . Thread synchronization is actually a waiting mechanism. When multiple threads access the same resource, they must enter a waiting pool to form a queue , waiting for the previous thread to be used up and the next thread to use it.
Insert picture description here
Queuing use mechanism.

Synchronize synchronization lock

Formation mechanism: queue + lock.
When a thread acquires an exclusive lock of an object, other threads must wait and wait for the thread to finish using it (open the lock) before using it.
What are the problems that are prone to using synchronization locks?

  • The thread must wait for the end of the previous thread before it can be used, which will cause program efficiency problems.
  • In the case of multiple threads and multiple resource object locks, a thread may occupy the resources to be used by another process, and it is in a state of waiting for the thread to release the lock. If the thread has been occupying the lock, then Will produce thread deadlock problem.
  • If a thread with a high priority waits for a thread with a lower priority to release the lock, it will affect performance issues (for example, many simple threads are waiting for a complex thread to process transactions, which will affect execution efficiency).

Synchronize synchronization lock : synchronization method and synchronization code block The
default lock of the synchronization method is this (the current object), and any object can become a lock.

   private synchronized  void buyTicket() {
        System.out.println(Thread.currentThread().getName() + ":我抢到了一个票" + ticketnum--);
        // 控制线程结束
        if (ticketnum <= 0) {
            falg = false;
        }
    }

Synchronization code block: generally use shared resources or resource objects that need to be manipulated as locks.

private   void buyTicket() {
        synchronized (this){   // Obj 代表任何资源对象
            System.out.println(Thread.currentThread().getName() + ":我抢到了一个票" + ticketnum--);
            // 控制线程结束
            if (ticketnum <= 0) {
                falg = false;
            }
        }
    }

PS: The thread sleep method is to let the thread rest and wait without releasing the lock. Wait is to let the thread enter the waiting area and release the lock.

What is thread deadlock?

Thread deadlock has actually been mentioned above. When multiple threads share some common resources and have more than two locks, they are all waiting for each other to release the lock, resulting in the thread being in a waiting state.
Example : I have a pen, but I need your paper to write, and you need my pen to write. But we are all waiting to let it go to ourselves, resulting in a state of waiting.
achieve:

// 笔对象
class Pen{}
// 纸对象
class Paper{}

// 写字
class Write implements Runnable{
    static  Pen pen = new Pen();
    static  Paper paper = new Paper();
    int flag;
    String name;
    Write(int flag,String name){
         this.flag = flag;
         this.name = name;
    }

    @Override
    public void run() {
        try {
            writeWork();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

public  void writeWork() throws InterruptedException {
        // 当flag 0时获取笔
        if(flag==0){
             synchronized (pen){
                System.out.println(name+":拿到了笔");
                Thread.sleep(2000);
                // 然后去拿纸的锁
                 synchronized (paper){
                     System.out.println(name+":拿到了纸");
                 }
             }
        }else {
            synchronized (paper){
                System.out.println(name+":拿到了纸");
                Thread.sleep(2000);
                // 然后去拿纸的锁
                synchronized (pen){
                    System.out.println(name+":拿到了笔");
                }
            }
        }
    }
}

/**
 * Created by 一只会飞的猪 on 2021/3/8.
 * 实现线程死锁现象,写字 = 笔 + 纸
 */
public class DeadLockThread {
    public static void main(String[] args) {
        new Thread(new Write(0,"小美")).start();
        new Thread(new Write(1,"小丑")).start();
    }
}

Result: Both Xiaomei and the clown held their own locks and waited for life.
Insert picture description here
How to solve the deadlock?
There is no good way to solve the deadlock. Generally, it is prepared to lock and release the lock on the object according to business needs. Take the example above.
We only need to let two people release the lock after getting one resource, and then get another resource.

public  void writeWork() throws InterruptedException {
        // 当flag 0时获取笔
        if(flag==0){
             synchronized (pen){
                System.out.println(name+":拿到了笔");
                Thread.sleep(2000);
             }
            // 然后去拿纸的锁
            synchronized (paper){
                System.out.println(name+":拿到了纸");
            }
        }else {
            synchronized (paper){
                System.out.println(name+":拿到了纸");
                Thread.sleep(2000);
            }
            // 然后去拿纸的锁
            synchronized (pen){
                System.out.println(name+":拿到了笔");
            }
        }
    }

Result: Both can be happy.
Insert picture description here
PS: Synchronize synchronization lock (implicit synchronization), after the implementation of the scope, the lock will be automatically released. The Lock lock (the next film) needs to actively release the lock (display synchronization)

Guess you like

Origin blog.csdn.net/qq_31142237/article/details/114552225