gpt4 book ai didi

java - 所有线程都获得锁?

转载 作者:行者123 更新时间:2023-12-02 03:28:00 25 4
gpt4 key购买 nike

获取锁后,线程应 hibernate 一定时间(本例中为 6000ms),以防止另一个线程获取锁。当我使用 l1.lock() 方法时,它工作正常,但是当我使用 l1.tryLock()l1.tryLock(1000,TimeUnit.MILLISECOND) 时,两个线程都在前一个线程释放锁之前获取锁。怎么可能?

import java.util.concurrent.locks.*;
import java.util.concurrent.locks.Lock;

class MyLocks implements Runnable {
static Lock l1;

public static void main(String... asd) {
l1 = new ReentrantLock();
MyLocks obj = new MyLocks();
new Thread(obj).start();
new Thread(obj).start();
}

public void run() {
System.out.println(Thread.currentThread().getName() + " is try to acquire lock");
try {
l1.trylock();
// only those thread which has acquired lock will get here.
System.out.println(Thread.currentThread().getName() + " has acquired lock");

Thread.sleep(6000);

} catch (Exception e) {
}
l1.unlock();
}
}

最佳答案

一个常见的错误是调用方法并忽略结果。您很可能正在运行

lock.tryLock(); // notice this ignores whether the lock was obtained or not.

当你应该做类似的事情时

while(!lock.tryLock(1, TimeUnit.SECOND)) {
System.out.println(Thread.currentThread().getName()+" - Couldn't get lock, waiting");
}

注意:不要丢弃异常,除非您非常确信它们不重要。

}catch(Exception e){} // something when wrong but lets pretend it didn't

有关如何处理异常的一些提示。

https://vanilla-java.github.io/2016/06/21/Reviewing-Exception-Handling.html

关于java - 所有线程都获得锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38520943/

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