• Post Reply Bookmark Topic Watch Topic
  • New Topic

why is the synchronised void prnt() not working?  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean by 'not working'?
Please read this page: It Doesnt Work Is Useless
 
Mannu Khanna
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not working as in the synchronized has no effect on the rest of the code. The output should have been [ hello ] [synchronised ] [ you ]
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mind power wrote:Not working as in the synchronized has no effect on the rest of the code. The output should have been [ hello ] [synchronised ] [ you ]



Can you explain to us why you think that synchronizing that method is supposed to generate that order?

Henry
 
Mannu Khanna
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
order is not the issue, so long as only one object can execute void prnt() at a time but the output : " [ synchronised[ you[ hello ] ] ]" (look at the square bracket) suggests otherwise.
 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mannu Khanna wrote:order is not the issue, so long as only one object can execute void prnt() at a time but the output : " [ synchronised[ you[ hello ] ] ]" (look at the square bracket) suggests otherwise.

That would be true it each thread was synchronizing on the same lock.
When you use synchronized keyword on non-static method it synchronizes on this.

Each of your printsync instances has of course different "this" so they are synchronizing using different objects as the lock.
If they are synchronizing on different locks it results in no (practical) synchronization at all.


The code I posted uses the same lock for every printsync object so the output is:
[ synchronised ] [ hello ] [ you ]

The order may vary.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!