gpt4 book ai didi

java - 如何写一个简单的公平锁?

转载 作者:行者123 更新时间:2023-12-01 15:27:15 24 4
gpt4 key购买 nike

如何编写一个简单的公平锁模拟新的ReentrantLock(true)

     public class Main1 {

public static void main(String[] args) {
// Lock lock = new ReentrantLock(true);
CustomLock lock = new CustomLock();
new Thread(new Producer(lock)).start();
new Thread(new Consumer(lock)).start();
}
}

class Producer implements Runnable {
private Lock lock;
private CustomLock customLock;

public Producer(Lock lock) {
this.lock = lock;
}

public Producer(CustomLock lock) {
this.customLock = lock;
}

@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// lock.lock();
customLock.lock();
System.out.println("Producer before");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Producer after");
// lock.unlock();
customLock.unlock();
}
}
}

class Consumer implements Runnable {
private Lock lock;
private CustomLock customLock;

public Consumer(Lock lock) {
this.lock = lock;
}

public Consumer(CustomLock lock) {
this.customLock = lock;
}

@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// lock.lock();
customLock.lock();
System.out.println("Consumer before");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Consumer after");
// lock.unlock();
customLock.unlock();
}
}
}

class CustomLock{
private boolean isLocked;

public synchronized void lock(){
while (isLocked) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;
}

public synchronized void unlock(){
if(isLocked){
isLocked = false;
notify();
}
}
}

自定义不公平锁(我不确定它是否正确)

class CustomLock{
private boolean isLocked;

public synchronized void lock(){
while (isLocked) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;
}

public synchronized void unlock(){
if(isLocked){
isLocked = false;
notify();
}
}
}

最佳答案

如果你想要一个公平的锁,你需要使用一个列表并按照列表顺序通知线程。

关于java - 如何写一个简单的公平锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10008774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com