Dict.CN 在线词典, 英语学习, 在线翻译 ------------- MyGitee 朱秋贵内科诊所 My腾云code

ReentrantLock 手动


Synchronized自动 关键字,完毕或异常后自动释放
Lock(aqs) 手动 获、释锁

 

public class TickerThread4 implements Runnable {

private int count=100;
private Lock lock=new ReentrantLock();

@Override
public void run() {
while (count>0){
ticket();
}
}

public void ticket(){
try {
Thread.sleep(30);
}catch (Exception e)
{

}
try{
lock.lock();
if(count>0)
{
System.out.println(Thread.currentThread().getName()+",当前系统余票【"+count+"】");
System.out.println(Thread.currentThread().getName()+",正在出票第【"+(100-count+1)+"】张");
count--;
}
}catch (Exception e){

}finally {
lock.unlock();
}

}

 

public static void main(String arg[])
{
TickerThread4 tickerThread=new TickerThread4();
new Thread(tickerThread,"售票机1号").start();
new Thread(tickerThread,"售票机2号").start();
}

}

posted @ 2021-04-01 09:45  cn2024  阅读(40)  评论(0编辑  收藏  举报