java 多线程传统锁:synchronized,Lock锁
传统锁:synchronized 是内置关键词,无法获取锁的状态
Lock锁:类 是否获取到锁,需手动释放锁
public class SaleTicketDem {
public static void main(String[] args) {
Ticket2 t=new Ticket2();
new Thread(()->{
for (int i = 0; i <40 ; i++) {
t.sale();;
}
},"a").start();
new Thread(()->{
for (int i = 0; i <40 ; i++) {
t.sale();;
}
},"b").start();
new Thread(()->{
for (int i = 0; i <40 ; i++) {
t.sale();;
}
},"c").start();
}
}
class Ticket2{
private int numer=30;
Lock lock=new ReentrantLock();
public void sale(){
lock.lock();
try {
if(numer>0){
System.out.println(Thread.currentThread().getName()+"卖出"+numer--+"票,剩余:"+numer);
}
}catch(Exception e){
e.printStackTrace();
}
finally {
lock.unlock();
}
}
}