Creating Thread: Implementing Runnable : Thread Creation « Thread « SCJP






class MainClass {
 public static void main(String args[]) {
  Thread thread1 = new Thread(new MyClass("thread1: "));
  Thread thread2 = new Thread(new MyClass("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);
 }
}
class MyClass implements Runnable {
 static String message[] = {"A","B","C","D","E","F"};
 String name;
 public MyClass(String id) {
  name = id;
 }
 public void run() {
  for(int i=0;i<message.length;++i) {
    try {
      Thread.currentThread().sleep((long)(3000*Math.random()));
     }catch (InterruptedException x){
      System.out.println("Interrupted!");
     }
   System.out.println(name+message[i]);
  }
 }

}
thread2: A
thread1: A
thread1: B
thread2: B
thread2: C
thread1: C
thread2: D
thread1: D
thread2: E
thread2: F
Thread 2 is dead.
thread1: E
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