Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

use String be the synchronized object

 
Song Xueyu
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,everyone,I'm studying the concurrent programing of Java.I saw a snippet like this:

The author of the snippet said that when you run it you will see "hello" and "world" are both printed on your screen.Right?Actually,I run the program and only the "hello" was printed.
Why?
It seems that the String sync will be changed in synchronized code-block and the condition of synchronization will absent.
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that in the code as you posted it, there is no concurrency, because the "run" method is called - which does not start a new thread, but executes in the current thread. That means line 19 is never reached because the code gets stuck in line 11.

If you call "start" instead of "run" in lines 18 and 19 you will observe the behavior the author described - because "start" starts a new thread in which the code is executed.
 
Song Xueyu
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Dittmer wrote:Note that in the code as you posted it, there is no concurrency, because the "run" method is called - which does not start a new thread, but executes in the current thread. That means line 19 is never reached because the code gets stuck in line 11.

If you call "start" instead of "run" in lines 18 and 19 you will observe the behavior the author described - because "start" starts a new thread in which the code is executed.


That's my problem!Thank you very much!
How careless I am!
 
Henry Wong
author
Sheriff
Posts: 22542
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ulf Dittmer wrote:
If you call "start" instead of "run" in lines 18 and 19 you will observe the behavior the author described - because "start" starts a new thread in which the code is executed.


Almost. There is a race condition, that may make it possible for only "hello" or "world" to be printed. If both threads hit the synchronization point at the exact same time (before any string references are changed), and both try to synchronize on the "aa" string, then only one thread will get to print.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!