1 /**
2 * 模拟抢票场景
3 */
4 public class ReentrantLockDemo {
5
6 private final ReentrantLock lock = new ReentrantLock();
7 private static int tickets = 8;
8
9 public void buyTicket() {
10 lock.lock();
11 try {
12 if (tickets > 0) {
13 try {
14 Thread.sleep(10);
15 } catch (InterruptedException e) {
16 e.printStackTrace();
17 }
18 System.out.println(Thread.currentThread().getName() + "购买了第" +
tickets-- + "张票");
19 } else {
20 System.out.println("票已经卖完了," + Thread.currentThread().getName() +
"抢票失败");
21 }
22
23 } finally {
24 lock.unlock();
25 }
26 }
27
28
29 public static void main(String[] args) {
30 ReentrantLockDemo ticketSystem = new ReentrantLockDemo();
31 for (int i = 1; i <= 10; i++) {
32 Thread thread = new Thread(() -> {
33
34 ticketSystem.buyTicket();
35
36 }, "线程" + i);
37
38 thread.start();
39
40 }
41
42
43 try {
44 Thread.sleep(3000);
45 } catch (InterruptedException e) {
46 throw new RuntimeException(e);
47 }
48 System.out.println("剩余票数:" + tickets);
49 }
50 }