CS 596: Client-Server Programming
Spring Semester, 1997
Doc 9, Threads part 2
To Lecture Notes Index
San Diego State University -- This page last updated Feb 25, 1997

Contents of Doc 9, Threads part 2
- The End of an Application
- Ending Thread Execution
- The Preferred Way
- Stop
- destroy
- Debugging Threads
When an program creates threads, what happens when the main ends before the
other threads?
Types of Threads: user and daemon
A program ends when the last user thread is finished
All daemon threads running when the program ends are stopped
Daemon example
class Test
{
public static void main( String args[] ) throws Exception{
InfinityThread shortLived = new InfinityThread( );
shortLived.setDaemon( true );
shortLived.start();
Thread.currentThread().sleep( 10 );
System.out.println( "Bye");
}
}
class InfinityThread extends Thread
{
public void run()
{
while (true)
{
System.out.println( "From: " + getName() );
System.out.flush();
yield();
}
}
}
Output
From: Thread-4
From: Thread-4
From: Thread-4
From: Thread-4
From: Thread-4
From: Thread-4
From: Thread-4
From: Thread-4
From: Thread-4
Bye
A thread ends when its run method returns
Forcing a Thread to Quit
Running thread checks to see if it is time to stop
class Test {
public static void main( String args[] ) throws Exception{
NiceThread missManners = new NiceThread( );
missManners.setPriority( 2 );
missManners.start();
Thread.currentThread().sleep( 5 );
missManners.pleaseStop();
}
}
class NiceThread extends Thread {
protected boolean stopRequested = false;
public void pleaseStop() { stopRequested = true; }
public void run() {
while (!stopRequested)
System.out.println( "From: " + getName() );
System.out.println( "The End" );
}
}
Output
From: Thread-2
From: Thread-2
From: Thread-2
From: Thread-2
From: Thread-2
The End
Forcing a Thread to Quit
class Test
{
public static void main( String args[] ) throws Exception
{
NotPoliteThread outOfMyWay = new NotPoliteThread( );
outOfMyWay.setPriority( 2 );
outOfMyWay.start();
Thread.currentThread().sleep( 5 );
outOfMyWay.stop();
}
}
class NotPoliteThread extends Thread
{
public void run()
{
while (1 < 2)
{
System.out.println( "From: " + getName() );
System.out.flush();
}
System.out.println( "The End" );
}
}
Output
From: Thread-2
From: Thread-2
From: Thread-2
From: Thread-2
From: Thread-2
Forcing a Thread to QuitThe Rambo Way
Do to the violent nature of destroy, no examples will be shown
Avoid using destroy, it does not allow any clean up to be done
Using destroy can leave other threads blocked forever
Some useful methods in Thread for debugging
public static void dumpStack()
- Prints a stack trace for the current thread on System.out
public String toString()
- Returns a String representation of the Thread, including the thread's name,
priority and thread group.
public int countStackFrames()
- Returns the number of stack frames in this Thread. The Thread must be
suspended when this method is called.