s-day06-synchornized代码块解决线程安全问题

This commit is contained in:
2026-08-06 11:22:55 +08:00
parent ecacfc7ead
commit 17f951ccc3
3 changed files with 57 additions and 2 deletions
@@ -0,0 +1,29 @@
package com.inmind.thread_safe_sychronized05;
//卖票任务:就是卖100张票
public class TicketTask implements Runnable{
int ticketCount = 100;//100张票
Object lock = new Object();//锁对象
@Override
public void run() {
//有票就卖
while (true) {
synchronized (lock){//这里是3个线程共享的同一个锁对象
//如果有票就卖
if (ticketCount > 0) {
//模拟卖票时间
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticketCount + "张票");
ticketCount--;
} else {
break;//结束循环
}
}
}
}
}