Java Reference
In-Depth Information
9.
10. public void setKeepGoing(boolean b) {
11. keepGoing = b;
12. }
13.
14. public void run() {
15. while(keepGoing) {
16. System.out.print(message + “ “);
17. try {
18. Thread.sleep(1000);
19. }catch(InterruptedException e) {}
20. }
21. System.out.println(“gone!”);
22. }
23. }
In the
run
method of
MyThread
, the
message
fi eld is printed in a
while
loop. The call
to
Thread.sleep
on line 18 causes the currently running thread (which is the
MyThread
instance) to sleep for at least 1,000 milliseconds (one second). Therefore, this
run
method
prints a
String
over and over again with at least a one-second delay between printings.
The following
Main
program instantiates and starts a
MyThread
object. Because this
example extended
Thread
, there is no need to instantiate two objects. (When implementing
Runnable
, you instantiate both the
Runnable
target and a
Thread
object.) The
MyThread
object represents both the thread object and the runnable target. Study the
Main
program
and see if you can determine its result:
1. public class Main {
2. public static void main(String [] args) {
3. MyThread myThread = new MyThread(“going”);
4. myThread.start();
5. try {
6. Thread.sleep(6000);
7. }catch(InterruptedException e) {}
8.
9. myThread.setKeepGoing(false);
10. System.out.println(“End of main”);
11. }
12. }
Search WWH ::
Custom Search