how2examples.com
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 ThreadExample.java:
public class ThreadExample {
   public static void main(String[] args) {
      for (int i=1; i<6; i++) {
         Runnable r = new A(i);
         r.run();
      }
      System.out.println();
      for (int i=1; i<6; i++) {
         Runnable r = new A(i);
         Thread t = new Thread(r);
         t.start();
      }
   }
}

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

   @Override
   public void run() {
      for (int i = 1; i<11; i++) {
         System.out.print(id);
         try {
            Thread.sleep(1);
         } catch (InterruptedException e) {
         }
      }
   }
}
Command to compile ThreadExample.java:
javac ThreadExample.java
Command to run ThreadExample:
java ThreadExample
Output from running ThreadExample:
11111111112222222222333333333344444444445555555555
12345214531243512354214532145321543125342154321354

The java.util.concurrent package

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


See Also