* Synchronized和Lock比较
* Synchronized自动释放锁、可重入锁非公平
* Lock必须手动释放、如果不释放会死锁、可重入锁非公平可以设置更改
public class Thread04 {
public static void main(String[] args) {
Ticket04 ticket = new Ticket04();
new Thread(()->ticket.sale(), "A").start();
new Thread(()->ticket.sale(), "B").start();
}
}
class Ticket04 {
int number = 1;
// ReentrantLock源码:
// sync = new NonfairSync();默认非公平锁
// FairSync公平锁先来后到、NonfairSync非公平锁可以插队
// public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); }
Lock lock = new ReentrantLock();
public void sale() {
lock.lock();
try {
if (number > 0) {
if (Thread.currentThread().getName().equals("A")) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
} finally {
lock.unlock();
}
}
}
领取专属 10元无门槛券
私享最新 技术干货