The use of Synchronized and Lock

Use of Synchronized

        Take ticket sales as an example

//基本的卖票例子

/*
    真正的多线程开发,公司中的开发,降低耦合性
    线程就是一个单独的资源类,没有任何附属的操作
    1.属性、方法
 */
public class SaleTicketDemo01 {
    public static void main(String[] args) {
        //多个线程操作同一个资源类
        Ticket ticket = new Ticket();

        //@FunctionalInterface 函数式接口,jdk1.8 lambda表达式 (参数)->{ 代码 }
        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        },"C").start();

    }

}

class Ticket {
    //属性、方法
    private int number = 50;

    //卖票的方式
    //synchronized 本质:队列,锁
    public synchronized void sale(){
        if (number>0){
            System.out.println(Thread.currentThread().getName()+"卖出了1张票,剩余"+--number+"张票");
        }
    }


}

Lock lock

        Need to manually lock and release the lock

  Lock lock is an interface, he has three implementation classes:

  • ReentrantLock class
  • ReentrantReadWriteLock.ReadLock
  • ReentrantReadWriteLock.WriteLock

        Take ticket sales as an example

//基本的卖票例子

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

/*
    真正的多线程开发,公司中的开发,降低耦合性
    线程就是一个单独的资源类,没有任何附属的操作
    1.属性、方法
 */
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        //多个线程操作同一个资源类
        Ticket2 ticket = new Ticket2();

        //@FunctionalInterface 函数式接口,jdk1.8 lambda表达式 (参数)->{ 代码 }
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                ticket.sale();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                ticket.sale();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                ticket.sale();
            }
        },"C").start();

    }

}

class Ticket2 {
    //属性、方法
    private int number = 15;

    Lock lock = new ReentrantLock();

    //lock三部曲
    //1. new ReentrantLock()
    //2.lock.lock(); //加锁
    //3.finally =>lock.unlock(); //解锁
    public synchronized void sale(){

        lock.lock(); //加锁


        try {
            //业务代码
            if (number>0){
                System.out.println(Thread.currentThread().getName()+"卖出了1张票,剩余"+--number+"张票");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();  //解锁
        }
    }

}

The difference between Lock lock and synchronized

  1. Synchronized is a built-in Java keyword; Lock is a Java class.
  2. Synchronized cannot determine the status of the lock acquisition; Lock can determine whether the lock has been acquired. (boolean b = lock. tryLock();)
  3. Synchronized will automatically release the lock; Lock must manually release the lock, if the lock is not released, deadlock.
  4. When Synchronized thread 1 obtains the lock and blocks, thread 2 will wait forever; when Lock lock thread 1 obtains the lock and blocks, thread 2 waits for a long enough time and interrupts the waiting to do other things.
  5. Synchronized reentrant lock, uninterruptible, unfair; Lock, reentrant lock, can judge the lock, unfair (can be manually set to a fair lock).
  6. Synchronized is suitable for locking a small amount of code synchronization issues; Lock is suitable for locking a large number of synchronization codes.

Guess you like

Origin blog.csdn.net/weixin_48426115/article/details/127895248