进阶day06-synchornized同步方法解决线程安全问题

This commit is contained in:
2026-03-07 16:02:08 +08:00
parent d9def2fa24
commit 9c67741e28
3 changed files with 78 additions and 12 deletions

View File

@@ -0,0 +1,29 @@
package com.inmind.syncnized_method06;
public class TicketTask implements Runnable{
//定义100张票电影票
int tickeCount = 100;
Object lock = new Object();//创建一个锁对象
@Override
public void run() {
//有票就卖
while (true) {
//使用同步代码块解决线程安全问题
//注意:一定是抢到锁对象的线程才能进入到同步代码块,执行代码,其他没有抢到的线程会被阻塞在此
synchronized (lock){
if (tickeCount > 0) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖第" + tickeCount + "张电影票");
tickeCount--;
} else {
break;
}
}
}
}
}