• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

synchronized run()

 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

What will the above code print?

I chose:
"It will keep on printin same values for x and y incrementing by 1 on each line."


but the correct answer given is:
"You cannot say anything about the values."

When I tried the program, I see output matching my answer. Any thoughts?

source :Enthuware
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When answering questions about what multiple threads output, you cannot always rely on what happens when you run the program on your machine a few times.

Sometimes you might get the output you saw, but it isn't guaranteed.

The main point to notice in that program is that the synchronized keyword modifies an instance method in the class definition.

That means that when that method is executed, the object that is locked is the current instance of the class.

Since there are two different instances of the class, when one instance executes run(), it does not block the other instance from executing its run() method.
 
Meena R. Krishnan
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Since there are two different instances of the class, when one instance executes run(), it does not block the other instance from executing its run() method.



Thanks Keith.
 
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For me, it's always a big help, to modify such a code by suggesting to yield the running thread to the JVM. So:

shows, what may happen if the running thread loses his running-state at a bad moment.
 
Attractive, successful people love this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic