The following exercises are designed to check your understanding of Java threads. Read each exercise, then write or paste your answers into the text area below.
- Create a class Tick that extends the Thread class. In the
run() method, loop 10 times. Each time through the loop have the current thread "go to sleep" for a random amount of time between 0 and 1 second and then use
System.out.println() to display "Tick".
- Create a class Tock that implements the Runnable interface. The behavior of the run() method of the Tock class should be the same as that of the Tick class except that "Tock" should be displayed each time through the loop.
- Create a test application called CrazyClock. In the main() method of this application create an instance of Tick and an instance of Thread with an instance of Tock as its target.
Next, simply start both threads. When this application executes you should observe a random sequence of the strings "Tick" and "Tock".
In the text box below, cut and paste the source code for Tick, Tock, and CrazyClock. Click, " Submit
to submit the code.