• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Thread Doubt

 
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class newqw implements Runnable {
public static void main(String[] args) {
new Thread(new newqw("Wallace")).start() ;
new Thread(new newqw("Gromit")).start();
}
private String name;
public newqw(String name) { this.name = name; }
public void run() {
message(1);
message(2);
}
private synchronized void message(int n) {
System.out.print(name + "-" + n + " ");
}
}

why is the above code printing different answers at different times? what should i do to get a same answer always?
 
Ranch Hand
Posts: 10198
3
Mac PPC Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,


why is the above code printing different answers at different times? what should i do to get a same answer always?



Dismantle your system and change your processor. Just kidding. This is what expected regarding the behaviour of thread. Thereads dont run the way you like, it is totally under the control of the JVM. You don't have to worry about this.

Regards,
Jothi Shankar Kumar. S
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I believe the problem is that you created a new Runnable object for each thread and you're using these different objects for synchronization. Since each thread is looking to obtain a different object lock (each thread is looking to obtain it's own Runnable object's lock) none of them will encounter a situation where they are blocked and cannot obtain the lock they're looking for, so really there's no sychronization.

I think one possible solution would be to create a static reference variable in the Runnable class (so just 1 lock is available) and sychronize the code in your run method on that (see below).

 
Maybe he went home and went to bed. And took this tiny ad with him:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic