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

This commit is contained in:
2026-08-06 11:55:24 +08:00
parent 17f951ccc3
commit 57733c44b3
@@ -9,7 +9,9 @@ public class TicketTask implements Runnable{
public void run() { public void run() {
//有票就卖 //有票就卖
while (true) { while (true) {
synchronized (lock){//这里是3个线程共享的同一个锁对象 //这里是3个线程共享的同一个锁对象
synchronized (lock){//同步代码块:只有拥有锁对象的线程才能进入同步代码块去执行
//synchronized (new Object()){//执行到这就创建锁对象,那就没有同一个锁对象,解决线程安全的效果(错误)
//如果有票就卖 //如果有票就卖
if (ticketCount > 0) { if (ticketCount > 0) {
//模拟卖票时间 //模拟卖票时间
@@ -23,7 +25,7 @@ public class TicketTask implements Runnable{
} else { } else {
break;//结束循环 break;//结束循环
} }
} }//当线程执行完毕该同步代码块之后,锁对象就会释放
} }
} }
} }