Java 如果我这样做会怎么样?(锁定) public void handleLinkWeights(LinkWeightMessage){//在发现所有边和对等点时计算最短路径。 peerLock.lock(); int size=m.weights.length;//所有列表的大小应相同 用于(int x=0;x

Java 如果我这样做会怎么样?(锁定) public void handleLinkWeights(LinkWeightMessage){//在发现所有边和对等点时计算最短路径。 peerLock.lock(); int size=m.weights.length;//所有列表的大小应相同 用于(int x=0;x,java,thread-safety,reentrantlock,Java,Thread Safety,Reentrantlock,如果我运行上面的代码,我会丢失锁吗?(代码不完整。) peerLock是一个 其余的可以从上下文推断。根据文档,我认为您不会丢失锁。它还利用了一个“保持计数”,如果同一线程再次尝试获取锁,该计数将增加 public void handleLinkWeights(LinkWeightMessage m) { //Calculate shortest paths when all edges and peers discovered. peerLock.lock(); int siz

如果我运行上面的代码,我会丢失锁吗?(代码不完整。)

peerLock
是一个


其余的可以从上下文推断。

根据文档,我认为您不会丢失锁。它还利用了一个“保持计数”,如果同一线程再次尝试获取锁,该计数将增加

public void handleLinkWeights(LinkWeightMessage m) { //Calculate shortest paths when all edges and peers discovered.
    peerLock.lock();
    int size = m.weights.length; //All lists should be the same size

    for (int x = 0; x < size; ++x){
        NodeMessage a = m.anodes.get(x),
                    b = m.bnodes.get(x);

        if (hasPeer(a.address, a.port)) {
            // ...
        }
    }

    peerLock.unlock();
    //TODO
}

private boolean hasPeer(String address, int port) {
    peerLock.lock();

    peerLock.unlock();
}
类似地,对于unlock(),保持计数递减,如果为零,则释放锁

public void lock()

Acquires the lock.

Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one.

If the current thread already holds the lock then the hold count is incremented by one and the method returns immediately.

If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one.

Specified by:
    lock in interface Lock 

因此,从文档中可以清楚地看到,从handleLinkWeights()调用hasPeer()的线程不会失去锁定。

您尝试过吗?您是否阅读了
ReentrantLock
的Javadoc?为什么您认为在本例中会丢失锁?我想知道调用has peer是否会导致我松开锁,因为它也有unlock。我没有看到任何关于调用也需要锁的方法的文档。我发现的大多数示例都使用同步。@JimGarrison,是的,我尝试过,但我想确保代码实际上是稳定的,而不仅仅是为我提供的内容工作。啊。如果你有工作代码要审查,有一个更好的网站:谢谢。我想看看会发生什么,我是否应该改变结构。
public void unlock()

Attempts to release this lock.

If the current thread is the holder of this lock then the hold count is decremented. If the hold count is now zero then the lock is released. If the current thread is not the holder of this lock then IllegalMonitorStateException is thrown.

Specified by:
    unlock in interface Lock
Throws:
    IllegalMonitorStateException - if the current thread does not hold this lock