当前位置: 首页>后端>正文

JUC:为什么需要Lock

JUC:为什么需要Lock,第1张

/**

* 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);

}

}

System.out.println(Thread.currentThread().getName() + "买票,现有" + number-- + ",剩余" + number);

}

} finally {

lock.unlock();

}

}

}


https://www.xamrdz.com/backend/3ue1923957.html

相关文章: