Threading Model   «Prev  Next»

Using Java Threads - Exercise

1)Extend Thread Class, 2) implement Runnable interface

Objective: Define, create, and start threads by both extending the Thread class and implementing the Runnable interface.

Exercise Scoring:

This exercise is worth 10 points.


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.
  1. 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".
  2. 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.
  3. 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.