10、Lock

package com.example.demo.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @projectName: demo
 * @package: com.example.demo.thread
 * @className: TestTiket
 * @author: 
 * @description: TODO
 * @date: 2021/12/8 16:02
 */
public class TestTicket2 {
    public static void main(String[] args) {
        Ticket2 ticket2 = new Ticket2();
        new Thread(ticket2, "学生").start();
        new Thread(ticket2, "程序员").start();
        new Thread(ticket2, "黄牛").start();
    }
}

class Ticket2 implements Runnable {
    private final ReentrantLock lock = new ReentrantLock();
    private int num = 10;

    @Override
    public void run() {
        this.buy();
    }

    private void buy() {
        while (true) {
            try {
                lock.lock();
                if (num <= 0) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + num);
                num--;
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

你可能感兴趣的:(10、Lock)