Java Reference
In-Depth Information
try
try
{
Thread
.
sleep
(
100
);
// in mSec
}
catch
catch
(
InterruptedException e
) {
return
return
;
}
}
System
.
out
.
println
(
mesg
+
" all done."
);
}
/**
* Construct a ThreadsDemo1 object.
* @param m Message to display
* @param n How many times to display it
*/
public
public
ThreadsDemo1
(
final
final
String mesg
,
int
int
n
) {
this
this
.
mesg
=
mesg
;
count
=
n
;
setName
(
mesg
+
" runner Thread"
);
}
/**
* Main program, test driver for ThreadsDemo1 class.
*/
public
public static
void
main
(
String
[]
argv
) {
// could say: new ThreadsDemo1("Hello from X", 10).run();
// could say: new ThreadsDemo1("Hello from Y", 15).run();
// But then it wouldn't be multi-threaded!
new
static
void
new
ThreadsDemo1
(
"Hello from X"
,
10
).
start
();
new
new
ThreadsDemo1
(
"Hello from Y"
,
15
).
start
();
}
}
What if you can't subclass
Thread
because you're already subclassing another class? There
are two other ways to do it: have a class implement the
Runnable
interface, or use an inner
nable
.
Example 22-2. ThreadsDemo2.java
public
public class
class
ThreadsDemo2
ThreadsDemo2
implements
implements
Runnable
{
private
private
String mesg
;
private
private
Thread t
;
private
private
int
int
count
;
/**