File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Two Threads with priorities Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Two Threads with priorities" Watch "Two Threads with priorities" New topic

Two Threads with priorities

Alexandru Gifei
Ranch Hand

Joined: May 19, 2012
Posts: 42

Hello guys,
I'm having an issue with 2 threads that run with different priorities. The problem is that the program prints the 2 counters, but does not stop. YThread is similar to XThread. Thanks

Life is not measured by the number of breaths we take, but by the moments that take our breath away.
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42959
Not sure if that's the problem , but you may want to declare isRunning as volatile - indicating its value can be altered in different threads.

From what I remember - you shouldn't rely on thread priorities for doing anything meaningful. Their implementation is (or used to be) very uneven and sometimes changed between JVM versions, so it is better not to rely on them. Maybe Henry will chime in on this, he'd know for sure.
Alexandru Gifei
Ranch Hand

Joined: May 19, 2012
Posts: 42

Declaring the flags as volatile did the job. Thanks!
Naresh Chaurasia
Ranch Hand

Joined: May 18, 2005
Posts: 361
Alexandru Gifei wrote:Declaring the flags as volatile did the job. Thanks!

True. I guess when the count is not volatile, the 2 threads tries to do code optimization by reading/writing the variable to cache/master location. Hence the 2 thread enter race condition and will not terminate.

SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
I agree. Here's the link:
subject: Two Threads with priorities
It's not a secret anymore!