• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread doubt (examlab question)

 
Emanuele Ghe
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
this code comes from an exam lab question:


The answer of this question is


In the explanation is stated that, even if the run() method is synchronized, there is no way to know
which thread will run first.

I think this explanation is misleading.
In my opinion the result is unpredictable because, since 2 threads are started with 2 different A objects, the synchronization is useless, because each object will acquire the lock on its A object independently from each other.

What do you think ?

p.s. I don't want to critic devaka work, is awesome. I just wanna be sure to understand everithing in the correct way.

Thanks.
 
Javier Cortes
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can indeed drop synchronized on the run method because, as you said, each Thread object is getting different locks when needed. Since synchronization was useless try and create a single object A and send it as target to both rba and rbb (don't synchronize either). You are at the same scenario here, sort of proof by contrapositive. Then, it all boils down to the fact that the JVM doesn't guarantee that the order in which the threads are started is going to be the order in which they'll become runnable.
 
Emanuele Ghe
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Javier Cortes wrote:You can indeed drop synchronized on the run method because, as you said, each Thread object is getting different locks when needed. Since synchronization was useless try and create a single object A and send it as target to both rba and rbb (don't synchronize either). You are at the same scenario here, sort of proof by contrapositive. Then, it all boils down to the fact that the JVM doesn't guarantee that the order in which the threads are started is going to be the order in which they'll become runnable.


Thank you, you confirmed my thoughts.
 
Deepa Sreedhara
Ranch Hand
Posts: 47
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Emanuele Ghe wrote:Hi,
this code comes from an exam lab question:


The answer of this question is




Hi,

Can someone tell me if the Thread constructor takes another Thread object with a Runnable target, as an argument. I know this code works but just want to know how it is understood?
Its quite an old topic, I hope its okay to post the example.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic