gpt4 book ai didi

java - 使用 ReentrantLock 时出现死锁

转载 作者:行者123 更新时间:2023-11-30 05:45:50 26 4
gpt4 key购买 nike

我使用ReentrantLock实现生产者消费者问题

public class Processor {
Lock lock = new ReentrantLock(true);
Condition condn = lock.newCondition();
public void produce() throws InterruptedException{
lock.lock();
System.out.println("inside producer method");
condn.await();
System.out.println("thread again wakeup");
lock.unlock();
}

public void consume() throws InterruptedException{
lock.lock();
Thread.sleep(1000);
condn.signal();
System.out.println("will i ever be ok ");
lock.unlock();
}


}

ReentrantLock 同步了两个方法,但有时进程会死锁

o/p我会好吗内部生产者方法

运行堆转储时

引用处理程序”#2 守护进程 prio=10 os_prio=31 cpu=0.26ms elapsed=540.35s tid=0x00007fd5f186f800 nid=0x4603 等待条件 [0x0000700002357000]

 java.lang.Thread.State: RUNNABLE
at java.lang.ref.Reference.waitForReferencePendingList(java.base@11.0.1/Native Method)
at java.lang.ref.Reference.processPendingReferences(java.base@11.0.1/Reference.java:241)
at java.lang.ref.Reference$ReferenceHandler.run(java.base@11.0.1/Reference.java:213)

"Finalizer" #3 daemon prio=8 os_prio=31 cpu=0.67ms elapsed=540.35s tid=0x00007fd5f1883000 nid=0x4303 in Object.wait() [0x000070000245a000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(java.base@11.0.1/Native Method)
- waiting on <0x0000000787f08f80> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(java.base@11.0.1/ReferenceQueue.java:155)
- waiting to re-lock in wait() <0x0000000787f08f80> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(java.base@11.0.1/ReferenceQueue.java:176)
at java.lang.ref.Finalizer$FinalizerThread.run(java.base@11.0.1/Finalizer.java:170)

"Signal Dispatcher" #4 daemon prio=9 os_prio=31 cpu=0.34ms elapsed=540.27s tid=0x00007fd5f1884000 nid=0x3903 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE


"Thread-0" #12 prio=5 os_prio=31 cpu=1.72ms elapsed=540.07s tid=0x00007fd5f00c7000 nid=0xa303 waiting on condition [0x0000700002d75000]
java.lang.Thread.State: WAITING (parking)
at jdk.internal.misc.Unsafe.park(java.base@11.0.1/Native Method)
- parking to wait for <0x0000000787ed4030> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.park(java.base@11.0.1/LockSupport.java:194)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(java.base@11.0.1/AbstractQueuedSynchronizer.java:2081)
at Processor.produce(Processor.java:11)
at RunnableExample$1.run(RunnableExample.java:13)
at java.lang.Thread.run(java.base@11.0.1/Thread.java:834)

为什么即使我使用释放锁后仍然会出现死锁

    condn.signal();

最佳答案

如果消费者先调用 consume,然后生产者调用 product,那么生产者将错过信号并陷入困境。

关于java - 使用 ReentrantLock 时出现死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849467/

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