JUC Lock实现类ReentrantLock使用说明

package 多线程练习.锁学习;

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

/*
   ReentrantLock 是属于JUC下面的可冲入锁是Lock接口的实现类
                 手动 上锁解锁
                 常用语 try{}finally{} 代码块中去开锁关锁,与 synchronized唯一的区别是 synchronized是在代码块中自动释放
 */
public class LockTest {

    public static void main(String[] args) {
        BuyTicketLock buy = new BuyTicketLock();
        new Thread(buy, "小明").start();
        new Thread(buy, "王老师").start();
        new Thread(buy, "黄牛党").start();
    }
}


class BuyTicketLock implements Runnable {

    private int ticketNum = 10;
    private Boolean flag = true;
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (flag) {
            buyTicket();
        }
    }

    public void buyTicket() {

        try {
            lock.lock();
            // 模拟延时操作
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 买票计划
            if (ticketNum > 0) {
                System.out.println(Thread.currentThread().getName() + "拿到了" + ticketNum-- + "张票");
            } else {
                flag = false;
                return;
            }
        } finally {
            lock.unlock();
        }

    }
}

 

输出结果

 

posted @ 2022-01-16 15:27  Chris丶Woo  阅读(49)  评论(0编辑  收藏  举报