Java Reference
In-Depth Information
public
public static
static
void
void
main
(
String
[]
argv
) {
new
new
ThreadsDemo3
(
"Hello from X"
,
10
);
new
new
ThreadsDemo3
(
"Hello from Y"
,
15
);
}
/**
* Construct a ThreadDemo object
* @param m Message to display
* @param n How many times to display it
*/
public
public
ThreadsDemo3
(
final
final
String mesg
,
int
int
n
) {
count
=
n
;
t
=
new
new
Thread
(
new
new
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."
);
}
});
t
.
setName
(
mesg
+
" runner Thread"
);
t
.
start
();
}
}
Here the
run()
method is part of the anonymous inner class declared in the statement begin-
ning
t = new Thread(…)
. This runs with no interaction with other classes, so it's a good use
of an inner class.
Finally, with Java 8, as shown in
Introduction
, you can in most cases simplify this code by
using a lambda expression in place of the anonymous inner class, as shown in
Example 22-4
.
Example 22-4. ThreadsDemo4.java
public
public class
class
ThreadsDemo4
ThreadsDemo4
{
private
private
String mesg
;
private
private
Thread t
;
private
private
int
int
count
;
/**
* Main program, test driver for ThreadsDemo4 class.