• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Paweł Baczyński
  • Piet Souris
  • Vijitha Kumara

Thread: Synchronized !

 
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:

 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • 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!'
 
The harder I work, the luckier I get. -Sam Goldwyn So tiny. - this ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!