Creating Threads: Subclassing the Thread Class : Thread Creation « Thread « SCJP

Home
SCJP
1.Java Source And Data Type
2.Operators
3.Modifiers
4.Type Casting
5.Statements
6.Object Oriented
7.Thread
8.Utility Classes
9.File
SCJP » Thread » Thread Creation 
7.1.6.Creating Threads: Subclassing the Thread Class
class MainClass extends Thread {
  static String message[] "A""B""C,""D,""E","F." };

  public static void main(String args[]) {
    MainClass thread1 = new MainClass("thread1: ");
    MainClass thread2 = new MainClass("thread2: ");
    thread1.start();
    thread2.start();
    boolean thread1IsAlive = true;
    boolean thread2IsAlive = true;
    do {
      if (thread1IsAlive && !thread1.isAlive()) {
        thread1IsAlive = false;
        System.out.println("Thread 1 is dead.");
      }
      if (thread2IsAlive && !thread2.isAlive()) {
        thread2IsAlive = false;
        System.out.println("Thread 2 is dead.");
      }
    while (thread1IsAlive || thread2IsAlive);
  }

  public MainClass(String id) {
    super(id);
  }

  public void run() {
    String name = getName();
    for (int i = 0; i < message.length; ++i) {
      try {
        sleep((long) (3000 * Math.random()));
      catch (InterruptedException x) {
        System.out.println("Interrupted!");
      }
      System.out.println(name + message[i]);
    }
  }
}
thread2: A
thread1: A
thread2: B
thread1: B
thread1: C,
thread1: D,
thread2: C,
thread2: D,
thread1: E
thread2: E
thread2: F.
Thread 2 is dead.
thread1: F.
Thread 1 is dead.
7.1.Thread Creation
7.1.1.The simplest way to define code to run in a separate thread is to
7.1.2.A summary of methods used with Threads.
7.1.3.The Life of a Thread
7.1.4.Create Thread method 1: subclass the Thread class and implement the run() method.
7.1.5.Create a Thread method 2: implements Runnable interface
7.1.6.Creating Threads: Subclassing the Thread Class
7.1.7.Creating Thread: Implementing Runnable
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.