资料内容:
1.2 ReentrantLock使用
独占锁:模拟抢票场景
8张票,10个人抢,如果不加锁,会出现什么问题?
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); // 休眠10ms,模拟出并发效果
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 }