gpt4 book ai didi

java - 调用notify()后什么时候锁才真正释放

转载 作者:行者123 更新时间:2023-12-01 17:48:31 25 4
gpt4 key购买 nike

我检查过代码,我只想知道我的理解是否正确。我有以下两个类(class)

public class WaitCheckWaiter implements Runnable
{

WaitCheck wc;

public WaitCheckWaiter( WaitCheck wc )
{
this.wc = wc;
}

@Override
public void run()
{
synchronized ( wc.strList )
{
wc.strList.add( "Added" );
System.out.println( "Notify for others" );
wc.strList.notifyAll();
for ( int i = 0; i < 100; i++ )
{
System.out.println( i );
}
try
{
Thread.sleep( 5000 );
}
catch ( InterruptedException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "Woke up" );
System.out.println( "After Notifying" );
}
System.out.println( "After synch WaitCheckWaiter" );

}

}

然后是下面这个

public class WaitCheck implements Runnable{

WaitCheck wc;
List<String> strList = new ArrayList();

public static void main(String[] args) {
WaitCheck wc = new WaitCheck();
new Thread(wc).start();
WaitCheckWaiter wcw = new WaitCheckWaiter(wc);
new Thread(wcw).start();
}



@Override
public void run() {
synchronized (strList) {
if(strList.size() == 0)
{
try {
System.out.println("Just Before wait..");
strList.wait();
System.out.println("Just after wait..");
// printing the added value
System.out.println("Value : "+strList.get(0));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println("In else statement..!!");
}
}
System.out.println("After synch WaitCheck");

}

}

所以我的理解是,即使我调用notifyAll(),等待线程也无法恢复,直到调用notifyAll()的同步块(synchronized block)完成为止。这是正确的还是有任何其他非确定性行为。

最佳答案

Javadoc for the Object.notifyAll method关于这个主题非常清楚:

(我将文字加粗)

Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

关于java - 调用notify()后什么时候锁才真正释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52802219/

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