Thread Safety Trilogy

thread safety

thread play
insert image description here

Synchronized code blocks (implicit locks)

In my thread's gameplay article, I described the problem that threads may be unsafe, and I provided a solution to the previous problem.

locked

Lock the thread, use the lock for security operations. Quickly recycle the digging operation, three threads open a lock. Perform thread operations. Let the code block of if be queued 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 image description here

Synchronized 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 locks and implicit locks

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

Sync: A keyword in Java, maintained by the JVM. It is a lock at the JVM level. Lock: It is a specific class that appeared after JDK5. Using Lock is to call the corresponding API. It is a lock at the API level. The bottom layer of Sync is locked by monitorenter (the bottom layer is done by monitor object, and methods such as wait/notify also depend on monitor object. Only in synchronized code blocks or synchronized methods can wait/notify and other methods be called. Because only in the synchronized code block or synchronized method, the JVM will call the monitor object); exit the lock through monitorexit. The Lock acquires and releases the lock by calling the corresponding API method.

Different ways to use

Sync is an implicit lock; Lock is an explicit lock.

The so-called explicit and implicit refers to whether the user should manually write code to acquire and release the lock when using it.

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 no logical problem, there will be no deadlock.
When using locks, our users need to manually acquire and release locks. If the lock is not released, it may lead to a deadlock phenomenon. Manually acquire the lock method: lock(); release the lock: unlock().
insert image description here

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324229291&siteId=291194637