Java Reference
In-Depth Information
Here is the output produced by the program:
Let's take a close look at this program. The heart of the clock is the TickTock class. It
contains two methods, tick( ) and tock( ) , which communicate with each other to ensure
that a Tick is always followed by a Tock, which is always followed by a Tick, and so on.
Notice the state field. When the clock is running, state will hold either the string "ticked"
or "tocked", which indicates the current state of the clock. In main( ) , a TickTock object
called tt is created, and this object is used to start two threads of execution.
The threads are based on objects of type MyThread . The MyThread constructor is
passed two arguments. The first becomes the name of the thread. This will be either "Tick"
or "Tock". The second is a reference to the TickTock object, which is tt in this case. Inside
the run( ) method of MyThread , if the name of the thread is "Tick", then calls to tick( )
are made. If the name of the thread is "Tock", then the tock( ) method is called. Five calls
that pass true as an argument are made to each method. The clock runs as long as true is
passed. A final call that passes false to each method stops the clock.
The most important part of the program is found in the tick( ) and tock( ) methods of
TickTock . We will begin with the tick( ) method, which, for convenience, is shown here:
Search WWH ::




Custom Search