Java Reference
In-Depth Information
5. this.greeting = greeting;
6. }
7.
8. public void run() {
9. for(int i = 1; i <= 10; i++) {
10. System.out.print(greeting);
11. }
12. System.out.println(“End of run”);
13. }
14. }
The
run
method on line 8 prints a
String
ten times. Line 12 prints
“End of run”
just
before the
run
method completes. Keep in mind that implementing
Runnable
does not
make the
SayHello
object a thread. An instance of
SayHello
needs to be associated with
a new
Thread
object, and then that
Thread
object is started by invoking its
start
method.
Only when the
start
method is invoked does an additional thread get added to the current
process.
The following
CountToTen
program starts a new
Thread
using a
SayHello
instance.
Study the code and see if you can determine its result:
public class CountToTen {
public static void main(String [] args) {
SayHello hello = new SayHello(“Hi”);
Thread t = new Thread(hello);
t.start();
for(int k = 1; k <= 10; k++) {
System.out.print(k);
}
System.out.println(“End of main”);
}
}
The output of the
CountToTen
programs looks like
12345678910End of main
HiHiHiHiHiHiHiHiHiHiEnd of run
Search WWH ::
Custom Search