01/10/2018, 09:26

Synchronized methods example, main and background thread

Hello Guys,

This is an example from Effective Java 2nd Ed, Joshua Bloch. Properly synchronized cooperative thread termination.
I found this program really strange concerning program flow. I put printlns into the author’s example as a help. The
main thread is going to terminate the backgroundThread after a millisecond. I would have thought that the backgroundThread
would run forever in the while loop. I was wrong because the main thread proceeds after executing the start of the backgroundThead
followed by the time delay and finally calling requestStop(). Meanwhile the background thread is incrementing var i and constantly
checking the stopRequested boolean.

Bloch writes “The actions of the synchronized methods in StopThread would be atomic even without synchronization. In other words, the synchronization on these methods is used solely for its communication effects, not for mutual exclusion.”

I didn’t find the right solution from the internet.
References:

  • https://www.java-forums.org/threads-synchronization/96107-synchronized-methods-example-main-background-thread.html
  • Sales animated video Examples.
Quân viết 11:41 ngày 01/10/2018

what is your question?

Bài liên quan
0