package com.lyon.juc; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class SaleTicketDemo02 { public static void main(String[] args) { Ticket1 ticket = new Ticket1(); new Thread(()->{ for (int i = 0; i < 40; i++) { ticket.sale(); } },"a").start(); new Thread(()->{ for (int i = 0; i < 40; i++) { ticket.sale(); } },"b").start(); new Thread(()->{ for (int i = 0; i < 40; i++) { ticket.sale(); } },"c").start(); } } //synchronized 与 Lock区别 //1.synchronized 是内置的java关键字,Lock是一个java类 //2.synchronized 无法判断获取锁的状态,Lock可以判断是否获取到了锁 //3.synchronized 会自动释放锁,lock必须要手动释放锁!如果不释放,死锁 //4.synchronized 线程1(获得锁,阻塞)、线程2(等待,一直等);Lock就不一定会等待下去;lock.tryLock();//尝试获取锁 //5.synchronized 为可重入锁,不可以中断的,非公平的;Lock锁,可重入锁,可以判断锁,非公平(源码中构造方法,true为公平,false为非公平,默认为false); //6.synchronized 适合锁少量的代码同步问题;Lock适合锁大量的同步代码! //lock class Ticket1{ private int number=30; //1.new ReentrantLock(); Lock lock = new ReentrantLock(); public void sale(){ //public synchronized void sale(){ //2.//加锁 lock.lock(); //lock.tryLock();//尝试获取锁 try{ if(number>0){ System.out.println(Thread.currentThread().getName()+"卖出了"+(number--)+"票"); } }catch (Exception e){ e.printStackTrace(); }finally { //3.解锁 lock.unlock(); } } }
多线程之synchronized与Lock的不同
最新推荐文章于 2021-12-11 16:57:53 发布