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重复嵌套