Java Reference
In-Depth Information
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName(“hello”);
System.out.println(“Starting hello thread...”);
thread1.start();
Runnable bye = new DisplayMessage(“Goodbye”);
Thread thread2 = new Thread(hello);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println(“Starting goodbye thread...”);
thread2.start();
System.out.println(“Starting thread3...”);
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{}
System.out.println(“Starting thread4...”);
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println(“main() is ending...”);
}
}
Let me make a few comments about the ThreadClassDemo program:
There are a total of five threads involved. (Don't forget the thread that
main() executes in.)
■■
thread1 and thread2 are daemon threads, so they will not keep the
process alive, which is relevant in this example because thread1 and
thread2 contain infinite loops.
■■
thread2 is assigned the minimum priority.
■■
The main() thread invokes join() on thread3. This causes main() to block
until thread3 finishes, which is an indefinite amount of time because
thread3 runs until it guesses the number 27.
■■
While main() is waiting for thread3, there are three runnable threads:
thread1, thread2, and thread3.
■■
When thread3 terminates, main() becomes runnable again and starts
thread4. Then main() ends and its thread dies, leaving thread1, thread2,
and thread4 as the remaining runnable threads of the process.
■■
thread4 runs until it guesses the number 75, at which point there are
only two daemon threads left. This causes the process to terminate.
■■
Search WWH ::




Custom Search