Thread introduction

In this chapter you will learn:

  1. Multithreaded Programming
  2. A counting thread

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.

Thread in action

The following code shows a pair of counting threads.

public class Main {
  public static void main(String[] args) {
    Runnable r = new Runnable() {
      @Override/*ja v  a2 s .c o  m*/
      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();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. Get and set Thread Name
  2. How to set thread name
Home » Java Tutorial » Thread
Thread introduction
Thread Name
Thread Main
Thread sleep
Thread Creation
Thread join and is alive
Thread priorities
Thread Synchronization
Interthread Communication
Thread Step
Thread suspend, resume, and stop
ThreadGroup
BlockingQueue
Semaphore
ReentrantLock
Executor
ScheduledThreadPoolExecutor