英文:
signallAll method in threads
问题
我正在阅读由Cay H. Hostmann所著的《Core Java I》一书,他在书中提供了关于线程的一些信息。他举了一个关于线程的例子,并且给出了一个具体的银行业务的例子。就像你知道的,在银行里,你可以转移资金,他想象了一次资金转移由一个线程实现。在第571页,他写道:
如果transfer方法发现资金不足,它会调用
"sufficientFunds.await();"
当前线程现在被停用并释放了锁。这样就可以让另一个线程进来,我们希望它能增加账户余额。
在等待获取锁的线程和已经调用了await的线程之间有一个重要的区别。一旦线程调用了await方法,它就会进入该条件的等待集合。当锁可用时,线程不会变为可运行状态。相反,它会保持停用状态,直到另一个线程在相同的条件上调用了signalAll方法。当另一个线程转移资金时,它应该调用
sufficientFunds.signalAll();
此调用重新激活所有等待该条件的线程。当这些线程从等待集合中移除时,它们会再次变为可运行状态,并且调度程序最终会再次激活它们。此时,它们将尝试重新进入对象。一旦锁可用,它们中的一个将获取锁,并继续之前的位置,从await调用中返回。
在最后一段中,他提到了"重新进入对象"(加粗)。他是什么意思?此外,他还提到了"从await调用中返回"。他是否意味着线程将从await函数调用的地方开始?
提前致谢。
英文:
I am reading the book, "Core Java I" written by Cay H. Hostmann and he gives some information about the threads. He gives an example about threads and he gives a concrete banking example. As you know, in a bank, you may transfer funds, and he imagined that one fund transfer has implemented by one thread. At page 571 he wrote:
> If the transfer method finds that sufficient funds are not available, it calls
>
> "sufficientFunds.await();"
>
> The current thread is now deactivated and gives up the lock. This lets in another thread that can, we hope, increase the account balance.
> There is an essential difference between a thread that is waiting to acquire a lock and a thread that has called await. Once a thread calls the await method, it enters a wait set for that condition. The thread is not made runnable when the lock is available. Instead, it stays deactivated until another thread has called the signalAll method on the same condition. When another thread has transferred money, it should call
> sufficientFunds.signalAll();
> This call reactivates all
> threads waiting for the condition. When the threads are removed from the wait set, they are again runnable and the scheduler will eventually activate them again. At that time, they will attempt to
> reenter the object. As soon as the lock is available, one of them will acquire the lock and continue where it left off, returning from the call to await.
In the last paragraph, he mentioned: "reenter the object" (in bold). What does he mean? Also, he mentioned "returning from the call to await." Does he mean that the thread will start off from the point where await function calls?
Thanks in advance.
答案1
得分: 1
通过“重新进入对象”,他的意思是线程将尝试在对象上执行受锁保护的方法。
而且,就在信号传递的那一点,等待的线程仍在执行等待方法,它从未离开过。线程进入了等待状态,在这种状态下,它不会被调度运行,接收到信号会唤醒它,然后它必须获取锁才能离开等待方法。
英文:
By “re-enter the object” he means the threads will try to execute the methods on the object (that are protected by the lock).
And yes, at the point it is signaled the waiting thread is still executing the await method, it never went anywhere. The thread went into a wait state where it doesn’t get scheduled to run, getting signaled wakes it up, then it has to acquire the lock in order to leave the await method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论