Class 2 |
Intermediate Java 30-IT-397 |
|
Selfish Threads
-
Threads should occasionally sleep or yeild, to give other threads a chance
to run.
-
sleep(int millis) makes a thread sleep for the specified number of milliseconds.
This gives a good opportunity for lower priority threads to run, since
this thread can't run for that time.
-
yeild() simply allows the operating system to pick a thread to run, including
the thread that is yeilding. Thus, if the highest priority thread
yeilds, there is a good chance that it will be selected to run again, and
other threads still will not have a chance to run.
-
If a thread does not sleep or yeild, it is considered selfish.
-
Let's take the sleep() call out of our previous program and see what happens
when we try to run additional threads.
-
This is not 100% predictable from system to system, since we know that
operating systems tend to handle threads in different ways.
-
The only code change was commenting out Thread.sleep(20); and changing
the call in public static void main(String args[]). Instead of re-posting
the code, I'll allow you to do that on your own.
-
As we see in the screen capture below, there is much less mingling of the
threads. A block of priority #2 runs, then #4, then #6. It
continues in that manner throughout the JList, with most threads running
in solid blocks.
Synchronization

Created by: Brandan Jones
December 17, 2001