• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronized Method sharing between threads  RSS feed

 
Sourabh Pujari
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am facing 1 problem while adding synchronized method sharing between 2 thread....

example:

I have an array which I need to be filled by 2 threads with number, the first thread will fill it with 1 & the other one will fill it with 7. so when I put synchronized on the method which fills array by giving only 1 thread the access of the method it should give me out put all 1's 10 times and then all 7's 10 or vice versa....however it dosent work in this manner and both the threads get into the method at a time.....

thanks for your help in advance...
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sourabh,

Next time you post code, please add code tags ([code][/code]) to make the code easier to read. I edited your post with the tags this time.

The reason there is no synchronization between the two threads is because the method is synchronized on the instance of the ReadWrite object. Since each thread has its own instance, there is no synchronization between them. What you need to do is either provide some shared Object that is the same between the two threads:



The other option is to use the same instance for both threads. (Sorry about no example - out of time for the moment)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!