369
Sams.net Learning Center
abcd
18
P2/V4/SQC5 TY Java in 21 Days 030-4 Casey 12.28.95
Ch 18 LP#3
until you interrupt the program. What if you want to be sure the two threads will take turns,
no matter what the system scheduler wants to do? You rewrite
RunnablePotato
as follows:
public class RunnablePotato implements Runnable {
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
Thread.yield(); // let another thread run for a while
}
}
}
Tip: Normally you have to say
Thread.currentThread().yield()
to get your hands
on the current thread, and then call
yield()
. Because this pattern is so common,
however, the
Thread
class provides a shortcut.
The
yield()
method explicitly gives any other threads that want to run a chance to begin
running. (If there are no threads waiting to run, the thread that made the
yield()
simply
continues.) In our example, there's another thread that's just dying to run, so when you now run
the class
ThreadTester
, it should output the following:
one potato
two potato
one potato
two potato
one potato
two potato
. . .
even if your system scheduler is non-preemptive, and would never normally run the second
thread.
PriorityThreadTester
To see whether priorities are working on your system, try this:
public class PriorityThreadTester {
public static void main(String argv[]) {
RunnablePotato aRP = new RunnablePotato();
Thread t1 = new Thread(aRP, "one potato");
Thread t2 = new Thread(aRP, "two potato");
t2.setPriority(t1.getPriority() + 1);
t1.start();
t2.start(); // at priority Thread.NORM_PRIORITY + 1
}
}
030-4s CH18.i
1/29/96, 11:57 AM
369