Threads

Thread

  • Each thread executes independently
  • The run method is essentially the main program for a thread

Methods for Creating a Threads

  • Subclass method
  • Exising class method
  • Lambda method

Subclass Method

  1. Define a subclass of Thread and override the run method (public void run())
  2. Create an object of that class and call its start method (which is inherited from Thread)

Threads1.java

// Threads1.java
// Creates threads using the subclass method.

public class Threads1 {
  // The subclass of thread overrides the run method.
  static class MyThread extends Thread {
    public void run() {
      for (int i = 0; i < 20; i++) {
        System.out.printf("Thread %2d: %3d\n", getId(), i);
      }
    }
  }
  public static void main(String[] argv) {
    MyThread[] threads = new MyThread[5];
    // Create the threads.
    for (int i = 0; i < 5; i++) {
      threads[i] = new MyThread();
    }
    // Start the threads.
    for (int i = 0; i < 5; i++) {
      threads[i].start();
    }
  }
}

Existing class method

  1. Declare that some exising class C implements Runnable and define a run method
  2. Create a thread passing an object of class C as an argument to the constructor
  3. Call the start method for the thread

Threads2.java

// Threads2.java
// Creates threads using an existing class.

public class Threads2 implements Runnable {
  public void run() {
    for (int i = 0; i < 10; i++) {
      System.out.printf("Thread: %2d %3d\n", Thread.currentThread().getId(), i);
    }
  }
  public static void main(String[] argv) {
    Threads2 program = new Threads2();
    Thread[] threads = new Thread[5];
    // Create the threads.
    for (int i = 0; i < 5; i++) {
      threads[i] = new Thread(program);
    }
    // Start the threads.
    for (int i = 0; i < 5; i++) {
      threads[i].start();
    }
  }
}

Define a run method using a lambda

  1. Create a thread passing a lambda which defines the run method as an argument to the constructor
  2. Call the start method for the thread.

Threads3.java

// Threads3.java
// Creates threads using a lambda.

public class Threads3 {
  public static void main(String[] argv) {
    Thread threads[] = new Thread[5];
    // Create the threads.
    for (int i = 0; i < 5; i++) {
      threads[i] = new Thread(() -> {
            for (int j = 0; j < 10; j++) {
              System.out.printf("Thread %2d: %3d\n", Thread.currentThread().getId(), j);
            }
        });
    }
    // Start the threads.
    for (int i = 0; i < 5; i++) {
      threads[i].start();
    }
  }
}