Java Reference
In-Depth Information
*/
public
public static
static void
void main ( String [] argv ) {
new
new ThreadsDemo4 ( "Hello from X" , 10 );
new
new ThreadsDemo4 ( "Hello from Y" , 15 );
}
/**
* Construct a ThreadDemo object
* @param m Message to display
* @param n How many times to display it
*/
public
public ThreadsDemo4 ( final
final String mesg , int
int n ) {
count = n ;
t = new
new Thread (() -> {
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." );
});
t . setName ( mesg + " runner Thread" );
t . start ();
}
}
To summarize, you can create a Runnable in one of several ways:
▪ Extend Thread as ThreadsDemo1 did. This works best for standalone applications that
don't need to extend another class.
▪ Implement the Runnable interface. This works for classes that extend another class and
thus cannot extend Thread due to single inheritance.
▪ Construct a Thread passing an inner class that is a Runnable . This is best for tiny run()
methods with little outside interaction.
▪ In Java 8, construct a Thread passing a lambda expression that is compatible with Run-
nable , which is a functional interface.
Search WWH ::




Custom Search