Threading Model   «Prev 


Extending the Thread class


The following program shows how to extend the Thread in order to implement a thread. When you compile and run the program, it will display a varying sequence of A's and B's, depending upon when thread A and thread B are able to execute. Later in this module, you will learn how to use synchronization to keep threads A and B from interfering with each other.

Extending the Thread class

class MyThread extends Thread {

  public static void main(String args[]) {
    MyThread threadA = new MyThread("A");
    MyThread threadB = new MyThread("B");
    threadA.start();
    threadB.start();
    while (threadA.isAlive() || threadB.isAlive()) {
       yield();
    }
    MyObject.displayResult();
  }

  public MyThread(String name) {
    super(name);
  }
 
  public void run() {
    for (int n = 0; n < 20; n++) {
      try {
        sleep((int)(Math.random() * 10.0));
      }
      catch (InterruptedException e) {}
      MyObject.update(getName()); 
    }
  }
}

class MyObject {
  static String result = "";

  public static void update(String name) {
    result += name;
  }
  public static void displayResult() {
    System.out.println(result);
  }
 
}