Multithreading-thread synchronization and deadlock-intermediate evolution 05

Multithreading-thread synchronization and deadlock-intermediate evolution 05

Multithreading problem: multiple threads access the same object, and some threads want to modify this thread

Thread synchronization is a kind of waiting mechanism, multiple threads accessing this object at the same time enter the waiting pool queue of this object

Concurrent

The same object is operated by multiple threads simultaneously

Queue and lock

Thread synchronization

Because multiple threads of the same process share the same storage space, in order to ensure the correctness of the data when accessed, the lock mechanism sychronized is added when accessing. When a thread obtains an exclusive lock of the object, it monopolizes the resource, and other threads must wait , Release the lock after use, but there are problems

  • A thread holding a lock will cause all other threads that need this lock to hang
  • Under multi-threaded competition, locking and releasing locks will cause more context switching and scheduling delays, causing performance problems
  • If a high-priority thread waits for a low-priority thread to release the lock, it will cause priority inversion and cause performance problems
package com.example.thread;

public class UnsafeBuyTickets {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "A").start();
        new Thread(buyTicket, "B").start();
        new Thread(buyTicket, "C").start();
    }
}

class BuyTicket implements Runnable {
    private int ticketNum = 10;
    boolean flag = true;

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

    public void buy() throws InterruptedException {
        if (ticketNum <= 0) {
            flag=false;
            return;
        }
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName()+"get"+ticketNum--);
    }

}

Synchronization method

The private keyword guarantees that the data object can only be accessed by the method. The mechanism proposed in the method is the sychronized keyword. There are two usages: sychronized method and sychronized code block

Synchronization method: public sychronized void method (int args) {}

The sychronized method controls access to the "object". Each object corresponds to a lock. Each sychroized method must obtain the lock of the object that calls the method before it can be executed. Otherwise, the thread will block. Once the method is executed, the lock will be exclusively used. The method returns to release the lock, and then the blocked thread can obtain the lock and continue execution

Defect, if a large method is declared as sychronized, it will affect efficiency

The content that needs to be modified in the method needs to be locked

Sync block

Synchronized block: sychronized (Obj){}

Obj calls it a sync monitor

Obj can be any object, but it is recommended to use shared resources as a synchronization monitor

In the synchronization method, the synchronization monitor is specified out of order, because the synchronization monitor of the synchronization method is this, which is the object, or class

The execution process of the synchronization monitor:

  1. The first thread accesses, locks the synchronization monitor, and executes the code
  2. The second thread visited and found that the synchronization monitor was locked and could not be accessed
  3. The first thread access is complete, unlock the synchronization monitor
  4. The second thread visits and finds that the synchronization monitor is not locked, then locks and visits

Deadlock

Multiple threads each occupy some shared resources and wait for the resources occupied by other threads to run. As a result, two or more threads are waiting for each other to release resources and all stop execution. A certain synchronization block has "two or more When the object is locked, a deadlock problem may occur

4 necessary conditions for deadlock

  1. Mutually exclusive conditions: 1 resource can only be used by 1 process at a time
  2. Request and hold conditions: when a process is blocked by requesting resources, keep the acquired resources
  3. Conditions of non-deprivation: the resources already acquired by the process have not been used up for duty, so they cannot be deprived forcibly
  4. Circulation waiting condition: a kind of cyclic waiting resource relationship is formed between several processes.

Avoid: destroy one of the 4 necessary conditions

Guess you like

Origin blog.csdn.net/rr18758236029/article/details/108580084