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