This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread: Synchronized !  RSS feed

 
Prathamesh Gaddam
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm trying to loop and print the twice however the output for the following code, is printed thrice, as:

Output:

run-single:
0
1
Thread[Thread-0,5,main]
A B C Thread[Thread-1,5,main]
A B C A B C

BUILD SUCCESSFUL (total time: 0 seconds)

Code:

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first thing in the code that looks wrong is this:

synchronized(new Object()) ...

You are creating a new object and synchronizing on that. However, each time you do this, you synchronize on a new, different object. This will not help with synchronization at all. If you want to synchronize two threads, you should synchronize on a single object. You can remove the whole 'synchronized' construct here, because it doesn't do anything.

What happens is, that the list is printed only two times. But the first time, the list contains "A", "B", "C", and the second time the list contains "A", "B", "C", "A", "B", "C" (it contains the letters two times!).
 
Prathamesh Gaddam
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Jesper, I just skipped/forgot the basics concentrating over threads.

So, should I need to modify the code as below, to synchronize the two threads.

synchronized(names)....

Jesper, a due request to clarify, towards my another query posted Today 9:59 AM with topic as 'Threads!'
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!