Java – the value of the nonvolatile variable during wait() and the notifyall() call in both threads

Suppose I have two threads a and B, and I have synchronization blocks in both threads, in which an int variable is continuously modified

@H_ 301_ 9@

@H_ 301_ 9@

notifyall(); //to wake thread B which is in waiting state and
wait():

Thread B then obtains the lock and performs the same steps as thread a, and continues to repeat the process All changes to the int variable occur in the synchronized block of the two threads@ H_ 301_ 9@

My problem is that I need to make the int variable volatile Before the thread acquires the lock because notifyall(), the thread refreshes the thread and reloads the data in the register before entering the waiting state; Call@ H_ 301_ 9@

Solution

If a and B run alternately rather than concurrently, and if they are closed by calling wait() and notifyall() on the same object, and if no other thread accesses the variable in question, thread safety does not require that the variable be volatile

@H_ 301_ 9@

Note that o.wait() and o.notifyall() must be called within a method or block synchronized on O – synchronization is sufficient to ensure that both threads see all writes to any variables from each other before shutting down@ H_ 301_ 9@

Be careful to ensure that two threads are synchronized on the same object, which is not clear in your problem If two threads are waiting and notifying different instances of the same class, there is no effective synchronization at all@ H_ 301_ 9@

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>