Multithreaded Programming

Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread. Each thread defines a separate path of execution.

Java's multithreading system is built upon the Thread class and Runnable interface. To create a new thread, your program will either extend Thread or implement the Runnable interface.

The Thread class defines several methods that help manage threads.

MethodMeaning
getNameObtain a thread's name.
getPriorityObtain a thread's priority.
isAliveDetermine if a thread is still running.
joinWait for a thread to terminate.
runEntry point for the thread.
sleepSuspend a thread for a period of time.
startStart a thread by calling its run method.

Thread declares several deprecated methods, including stop(). These methods have been deprecated because they are unsafe. Do not use these deprecated methods.

The following code shows a pair of counting threads.

 
public class Main {
  public static void main(String[] args) {
    Runnable r = new Runnable() {
      @Override
      public void run() {
        String name = Thread.currentThread().getName();
        int count = 0;
        while (count< Integer.MAX_VALUE)
          System.out.println(name + ": " + count++);
      }
    };
    Thread thdA = new Thread(r);
    Thread thdB = new Thread(r);
    thdA.start();
    thdB.start();
  }
}
  

The following code sets name to threads.

 
public class Main {
  public static void main(String[] args) {
    Runnable r = new Runnable() {
      @Override
      public void run() {
        String name = Thread.currentThread().getName();
        int count = 0;
        while (count<Integer.MAX_VALUE) {
          System.out.println(name + ": " + count++);
          try {
            Thread.sleep(100);
          } catch (InterruptedException ie) {
          }
        }
      }
    };
    Thread thdA = new Thread(r);
    thdA.setName("A");
    Thread thdB = new Thread(r);
    thdB.setName("B");
    thdA.start();
    thdB.start();
  }
}
  
Home 
  Java Book 
    Thread Conncurrent  

Thread:
  1. Multithreaded Programming
  2. The Main Thread
  3. Thread Name
  4. Thread sleep
  5. Thread Creation
  6. isAlive( ) and join( )
  7. Thread Priorities
  8. Thread Synchronization
  9. Interthread Communication
  10. Suspending, Resuming, and Stopping Threads
  11. Handle Uncaught Exception
  12. ThreadLocal variables