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();
}
}
}

posted @ 2024-11-27 19:39  大树2  阅读(2)  评论(0编辑  收藏  举报