This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes setPriority not working as expected Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "setPriority not working as expected" Watch "setPriority not working as expected" New topic
Author

setPriority not working as expected

Jason Anderson
Greenhorn

Joined: Apr 21, 2002
Posts: 2
I'm trying to teach myself about threads for the certification exam. I wrote the following sample code:

I would expect this to output:
Thread5
Thread4
Thread3
Thread2
Thread1
However, it prints:
Thread5
Thread3
Thread4
Thread1
Thread2
Can anyone tell me why this isn't running the threads in order of priority?
Thanks,
Jason
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Thread scheduling is always up to the specific underlying implementation. You don't really have control in java to affect this. You can make *suggestions* to the Thread scheduler, such as calling Thread.yield() or setting a thread's priority, but there's no guarantee that these calls will be used for anything.


Rob
SCJP 1.4
Jason Anderson
Greenhorn

Joined: Apr 21, 2002
Posts: 2
Thank you, Rob. I appreciate the help.
Peter Haggar
author
Ranch Hand

Joined: Jan 03, 2001
Posts: 106
This creates problems when you want to control the order of execution of waiting threads. You can't rely on priority, or on which thread has been waiting the longest, even on the same JVM. To control the order of waiting threads you can use the specific notification pattern. Details and programming examples are here.
Peter Haggar


Senior Software Engineer, IBM
author of: Practical Java
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: setPriority not working as expected
 
Similar Threads
static synchronized method
some problems regd threads as in velmurugan's notes
Threads not running concurrent?
I Cannot Get My Thread Program Compiled
Output to a file