package com.haohao.test;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author zhh
* @description
* @date 2020/9/16
*/
public class TestLock {
public static void main(String[] args) {
MyLock lock = new MyLock();
new Thread(lock).start();
new Thread(lock).start();
new Thread(lock).start();
}
static class MyLock implements Runnable {
private int ticketNum = 10;
// 定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();// 加锁
if (ticketNum > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNum--);
} else {
break;
}
} finally {
// 解锁
lock.unlock();
}
}
}
}
}
输出结果:
10
9
8
7
6
5
4
3
2
1