
package com.heima.dainyingpaio;
public class sale extends Thread{
static int picket = 0;
// static Object o = new Object();
@Override
public void run() {
while (true) {
synchronized(sale.class) {//同步代码块-锁
if (picket < 100) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
picket++;
System.out.println(getName() + "卖出第" + picket + "张票");
} else {
break;
}
}
}
}
}
-------------------------------------------
Lock手动上锁
public class sale3 implements Runnable{
//锁-手动锁lock,使用前需创建ReentrantLock对象
int ticket = 0;
Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
lock.lock();
try {
if(ticket == 100){
break;
}else{
Thread.sleep(10);
ticket++;
System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票");
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
}
死锁:两个synronized重复嵌套
Java多线程同步:synchronized与ReentrantLock实现售票,
文章展示了在Java中如何使用synchronized关键字和ReentrantLock实现线程安全的售票系统,以及讨论了死锁的概念,通过一个例子说明了两个同步块嵌套可能导致的死锁问题。
1109

被折叠的 条评论
为什么被折叠?



