up in exactly the specified time. Other thread scheduling can interfere, as can
the granularity and accuracy of the system clock, among other factors. If the
thread is interrupted while it is sleeping, then an
InterruptedException is thrown.
public static voidsleep(long millis, int nanos)tHRows
InterruptedException
Puts the currently executing thread to sleep for at least the specified number
of milliseconds and nanoseconds. Nanoseconds are in the range 0999999.
public static voidyield()
Provides a hint to the scheduler that the current thread need not run at the
present time, so the scheduler may choose another thread to run. The
scheduler may follow or ignore this suggestion as it sees fityou can generally
rely on the scheduler to "do the right thing" even though there is no
specification of exactly what that is.
The following program illustrates how yield can affect thread scheduling. The application takes a list of
words and creates a thread for each that is responsible for printing that word. The first parameter to the
application says whether each thread will yield after each println; the second parameter is the number of
times each thread should repeat its word. The remaining parameters are the words to be repeated:
class Babble extends Thread {
static boolean doYield; // yield to other threads?
static int howOften; // how many times to print
private String word; // my word
Babble(String whatToSay) {
word = whatToSay;
}
public void run() {
for (int i = 0; i < howOften; i++) {
System.out.println(word);
if (doYield)
Thread.yield(); // let other threads run
}
}
public static void main(String[] args) {
doYield = new Boolean(args[0]).booleanValue();
howOften = Integer.parseInt(args[1]);
// create a thread for each word
for (int i = 2; i < args.length; i++)
new Babble(args[i]).start();
}
}
When the threads do not yield, each thread gets large chunks of time, usually enough to finish all the prints
without any other thread getting any cycles. For example, suppose the program is run with doYield set to
false in the following way:
Babble false 2 Did DidNot