Lock是个接口所以得用它的实现类ReentrantLock
void lock() 加锁
void unlock() 释放锁
具体用法:
public class SellTicket implements Runnable {
private int ticket = 100;
//加锁对象
Lock lock=new ReentrantLock();
@Override
public void run() {
while (true) {
//一般加try然后就finally
try {
//加锁
lock.lock();
if (ticket > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在买" + (ticket--) + "张票");
}
}finally {
//释放锁
lock.unlock();
}
}
}
}