Java Multitasking  «Prev 

Java Morse Code - Exercise

Creating and starting Threads

In this exercise, you will create a new Thread subclass that can be used in conjunction with a Java class called Morse:
class Morse {
   public static void main(String[] args) {
      DotDash d1, d2, d3;
      d1 = new DotDash('.');
      d2 = new DotDash('-');
      d3 = new DotDash(' ');
      d1.start();
      d2.start();
      d3.start();
   }
}

This Thread subclass is called DotDash. When you execute the Morse class, its main() method will create and start three different DotDash threads. These threads will display random Morse code output.

Implement threads in Morse.java

Here is what your DotDash thread should do:
  1. Define an instance variable of type char.
  2. Assign the value to this instance variable in a special constructor for DotDash that takes a char value.
  3. In the run() method, loop 100 times.
  4. In the loop, use System.out.print() to display the char value in the standard output.
  5. Also in the loop, include the following line of code so that the thread "goes to sleep" for a small, random amount of time.

try{
  sleep((int)(Math.random() * 10));
}
catch (InterruptedException e){
  e.printStackTrace();
}
Your random Morse code output will look something like this:

Morse Code Output

. .- .-.- .- .-  -. -. -. -..- . - .. -.- -. 
. -. -.  ..- . -.- - . -. - -. .-.
 .- --- . ..- .... -. .       -. - .-.--- 
.- - .- . -. -. -.---.- .- --.-  . ---
 . . .- .-. -. ---. -  . - - -.- . -.-. -   
 -. . . -. -. ...-   -. . . . -. --.
- . . . .   -. -
Copy and paste your new Thread subclass into the text area below: