Java Reference
In-Depth Information
* Main program, test driver for ThreadsDemo2 class.
*/
public
public static
static void
void main ( String [] argv ) {
new
new ThreadsDemo2 ( "Hello from X" , 10 );
new
new ThreadsDemo2 ( "Hello from Y" , 15 );
}
/**
* Construct a ThreadsDemo2 object
* @param m Message to display
* @param n How many times to display it
*/
public
public ThreadsDemo2 ( String m , int
int n ) {
count = n ;
mesg = m ;
t = new
this );
t . setName ( m + " runner Thread" );
t . start ();
new Thread ( this
}
/** Run does the work. We override the run() method in Runnable. */
public
public void
void run () {
while
while ( count -- > 0 ) {
System . out . println ( mesg );
try
try {
Thread . sleep ( 100 );
// 100 msec
} catch
catch ( InterruptedException e ) {
return
return ;
}
}
System . out . println ( mesg + " thread all done." );
}
}
The run() method itself does not change, so I've omitted it from this listing. Example 22-3
is a version of this class that uses an inner class to provide the run() method.
Example 22-3. ThreadsDemo3.java
public
public class
class ThreadsDemo3
ThreadsDemo3 {
private
private Thread t ;
private
private int
int count ;
/**
* Main program, test driver for ThreadsDemo3 class.
*/
Search WWH ::




Custom Search