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

}

原文地址:https://www.cnblogs.com/smallfa/p/14604886.html