44-10Lock接口

97 阅读1分钟
locks.Lock接口: 比同步方法/同步代码块使用更灵活
lock(): 获取锁。
unlock(): 释放锁。  释放资源的动作必须要执行
ReentrantLock类 是一个锁对象,在使用的时候,务必要保证锁对象的唯一性
Lock接口替换了同步代码块和同步方法
 使用格式:
            上锁: lock.lock();
            try {
                操作共享数据的代码;
            } catch(...){
                ...
            } finally {
                //释放锁的代码
                lock.unlock();
            }
            

Lock接口替换同步

/*
    使用Lock锁对象替换同步代码块
 */
@SuppressWarnings("All")
//创建Runnable接口实现类
public class MyTicketsTask01 implements Runnable {
    //共享资源
    private int num = 100;
   //使用Lock锁对象替换同步代码块
    //保证锁对象的唯一性
    private Lock lock = new ReentrantLock();//多态
    @Override
    public void run() {
            //同步代码块
        while(true) {
                        
            try {
                //获取锁对象
                lock.lock();
                if (num > 0) {
                    Thread.sleep(10);
                    String threadName = Thread.currentThread().getName();
                    System.out.println(threadName+"正在卖出第....."+num+".....张票");
                    num--;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //释放锁对象的操作必须要被执行
                lock.unlock();
            }
        }
    }
}
//测试类
public class Demo01Tickets {
    public static void main(String[] args) {
        //创建线程任务对象
        MyTicketsTask02 task = new MyTicketsTask02();

        //创建线程对象
        Thread t1 = new Thread(task, "窗口");
        Thread t2 = new Thread(task, "手机APP");
        Thread t3 = new Thread(task, "网站");

        //开启线程
        t1.start();
        t2.start();
        t3.start();
    }
}