Thread safety trilogy

Thread safe

How to play threads
Insert picture description here

Synchronous code block (implicit lock)

In the article on how to play threads, I talked about the possible insecurity of threads, and I provided a solution to the previous problems.

Locked

Lock the thread and use the lock for security operations. The quick recovery operation, three threads open a lock. Perform thread operations. Let the code block of the if queue for execution.

package work.february.five;

import work.february.three.Demo8;

/**
 * @Author: 小浪
 * @Description:
 * @Date Created in 2021-02-05 14:01
 * @Modified By:
 */
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        //设置线程锁
        Runnable runnable=new Ticket();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();


    }
        static class Ticket implements Runnable{
    
    
           private int count =10;
           private Object object =new Object();
            @Override
            public void run() {
    
    

                while (true) {
    
    
                    synchronized (object){
    
    
                    if (count > 0) {
    
    

                        System.out.println(Thread.currentThread().getName()+"正在准备取票:");
                        try {
    
    
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
    
    
                            e.printStackTrace();
                        }
                        count--;
                        System.out.println("出票成功,余票:" + count);
                    }
                }
            }
        }
    }
}


Insert picture description here

Synchronization method

Method lock

package work.february.five;

/**
 * @Author: 小浪
 * @Description:
 * @Date Created in 2021-02-05 14:38
 * @Modified By:
 */
public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        //设置线程锁
        Runnable runnable=new Demo.Ticket();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();


    }
    static class Ticket implements Runnable{
    
    
        private int count =10;

        @Override
        public void run() {
    
    

            while (true) {
    
    
                boolean flag =sale();
                if(!flag){
    
    
                    break;
                }

            }
        }
        public synchronized boolean sale(){
    
    
            if (count > 0) {
    
    
                System.out.println(Thread.currentThread().getName()+"正在准备取票:");
                try {
    
    
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                count--;
                System.out.println("出票成功,余票:" + count);
                return true;
            }
            return false;
        }
    }

}

Show lock

package work.february.five;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 小浪
 * @Description:
 * @Date Created in 2021-02-05 15:01
 * @Modified By:
 */
public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        //设置线程锁
        Runnable runnable=new Demo.Ticket();
        new Thread(runnable).start();
        new Thread(runnable).start();
        new Thread(runnable).start();


    }
    static class Ticket implements Runnable{
    
    
        private int count =10;
        private  Lock  l=new ReentrantLock();
        @Override
        public void run() {
    
    

            while (true) {
    
    
                //显式锁
                    l.lock();
                    if (count > 0) {
    
    
                        System.out.println(Thread.currentThread().getName()+"正在准备取票:");
                        try {
    
    
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
    
    
                            e.printStackTrace();
                        }
                        count--;
                        System.out.println("出票成功,余票:" + count);
                    }
                    l.unlock();
                }

        }
    }
}

The difference between explicit lock and implicit lock

The origins (original composition) of Sync and Lock are different:

Sync: The keywords in Java are maintained by the JVM. It is a lock at the JVM level. Lock: It is a specific class that only appeared after JDK5. To use Lock is to call the corresponding API. It is a lock at the API level. The bottom layer of Sync is locked through the monitorenter (the bottom layer is completed by the monitor object, and the wait/notify methods are also dependent on the monitor object. Only in the synchronized code block or synchronized method can the wait/notify method be called. Because only in the synchronization code block or synchronization method, the JVM will call the monitor object); exit the lock through monitorexit. The Lock is to acquire and release the lock by calling the corresponding API method.

Different methods of use

Sync is an implicit lock; Lock is a display lock.

The so-called display and implicit is when the user wants to manually write code to acquire and release the lock when in use.

When using the sync keyword, the program can automatically acquire and release locks. That's because when the sync code block is executed, the system will automatically let the program release the occupied lock. Sync is maintained by the system, if there is a non-logical problem, there will be no deadlock.
When using lock, our users need to manually acquire and release the lock. If the lock is not released, it may lead to a deadlock. Manually acquire the lock method: lock(); release the lock: unlock().
Insert picture description here

When you see this, don't be stingy with the likes in your hand, give a free like and follow! If you have any questions, you can contact Xiaolang: [email protected], or private message.

Guess you like

Origin blog.csdn.net/AzirBoDa/article/details/113694430