Home - Introduction to Java Programming

Java Threads

A thread is a "thread of execution". By having multiple threads, an application can give the apperance of doing more than one thing at a time. The illusion of an application performing tasks in parral, even on a single processor machine, is made possible by time-slicing. With time slicing, threads take it in turn to have access to the CPU for short periods at a time.

Thread Lifecycle

A thread remains in a "ready" state until the thread scheduler allows it to enter the "running" state. Only when it is in the "running" state does a thread get to execute. There a number of reasons why a thread may exit the "running" state:

Creating Threads

Threads are represented in Java by the java.lang.Thread class. There are two ways to get functionality running in a seperate Thread:

Contents of
public class ThreadExample {
   public static void main(String[] args) {
      for (int i=1; i<6; i++) {
         Runnable r = new A(i);;
      for (int i=1; i<6; i++) {
         Runnable r = new A(i);
         Thread t = new Thread(r);

class A implements Runnable {
   private final int id;
   A(int id) { = id;

   public void run() {
      for (int i = 1; i<11; i++) {
         try {
         } catch (InterruptedException e) {
Command to compile
Command to run ThreadExample:
java ThreadExample
Output from running ThreadExample:

The java.util.concurrent package

Java 5 introduced a new java.util.concurrent package containing high-level concurrency features.

See Also