s-day06--Lock接口的使用(了解)

This commit is contained in:
xx
2026-10-19 15:54:15 +08:00
parent 9c63edf504
commit c7f0c0dba0
2 changed files with 57 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
package com.inmind.lock07;
/*
Lock接口,有一个常用的实现类ReentrantLock
常用方法:
void lock() 获得锁。
void unlock() 释放锁。
*/
public class Demo07 {
public static void main(String[] args) {
//多个窗口来卖票
//1.创建1个卖票的任务
TicketTask ticketTask = new TicketTask();
//2.创建3个窗口(线程),执行卖票的任务
new Thread(ticketTask,"窗口1").start();
new Thread(ticketTask,"窗口2").start();
new Thread(ticketTask,"窗口3 ").start();
}
}
@@ -0,0 +1,36 @@
package com.inmind.lock07;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
// 1.定义卖票任务,只有100张票,有票就卖
public class TicketTask implements Runnable{
int ticketCount = 100;//100张票
Lock lock = new ReentrantLock();//接口的多态
@Override
public void run() {
//有票就卖
while (true) {
//加锁
lock.lock();
//具有线程安全问题的代码
if (ticketCount > 0) {
//卖票:需要耗时5ms
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticketCount + "张票");
ticketCount--;
} else {
// 没有票就关闭售票窗口
break;
}
//释放锁
lock.unlock();
}
}
}