Header javaperspective.com
JavaPerspective.com  >   Intermediate Tutorials  >   2. Concurrency  >   2.1. Threads

2.1. Threads
Last updated: 29 January 2013.

This tutorial will show you how to create and run threads.


2.1.1. How to create a thread

Creating a thread is very simple. You can do it in two different ways:
In both cases, the method run contains the code that will be executed by the thread. When the method run terminates, the thread dies.

As an example, the class MyThread1 shown below is a thread that extends the class Thread and simply prints Hello World to the standard output:

public final class MyThread1 extends Thread {

   
public void run(){
         
System.out.println("Hello World");
   
}

}

In the example shown below, the class MyThread2 implements the interface Runnable and prints Hello World to the standard output:

public final class MyThread2 implements Runnable {

   
public void run(){
         
System.out.println("Hello World");
   
}

}



2.1.2. How to run a thread

To run a thread, call the method start provided by the class Thread. For example, the class App shown below contains a main method that creates an instance of the class MyThread1 and calls its method start:

public final class App {

   
public static void main(String[] args){
         
new MyThread1().start();
   
}

}

In the following example, the class App creates a thread by passing to the constructor Thread(Runnable target) an instance of the class MyThread2. Then the method start is called:

public final class App {

   
public static void main(String[] args){
         
new Thread(new MyThread2()).start();
   
}

}

In both cases, the method start is called. As a result, the method run is invoked. You should never call the method run explicitly to start a thread. The method start can be called only once. If you call it more than once, an IllegalThreadStateException will be thrown.

When the main method provided by the class App is executed, it runs in its own separate thread. Consequently, when that main thread creates and runs a new thread, two threads are actually running concurrently.


2.1.3. The sleep method

The sleep method provided by the class Thread allows you to make a thread cease its execution for a given number of milliseconds. As an example, the class Sleeper shown below prints for 5 times Hello World to the standard output. At each iteration, the thread sleeps for one second:

public final class Sleeper extends Thread {

   
public Sleeper(){
         
setName("Sleeper");
   
}

   
public void run(){
         
for(int i=0; i<5; ++i){
               
try{
                     
System.out.println("Hello World");
                      Thread.sleep
(1000);
               
}
               
catch(InterruptedException e){

                }
          }
    }

}

As you can see, the class Sleeper has a constructor wherein the method setName provided by the class Thread is called in order to give a name to the thread. It is good programming practice to name threads. That way, you can easily identify them if you are using a profiling tool that displays the currently running threads of your application on a graphical user interface. If you don't name a thread, the method getName provided by the class Thread returns an automatically generated name that looks something like Thread-0. Thus, if you run multiple threads at a time, they would appear on a profiling tool as Thread-0, Thread-1, Thread-2 and so forth, making it impossible to match a thread name with a class of your application.

In the code above, the exception InterruptedException is handled because it is a checked exception that must be handled at compile time. The sleep method throws an InterruptedException when the method interrupt is called by another thread under certain circumstances as you will see in the section 2.1.5 (The interrupt method).

The class App creates and runs an instance of the class Sleeper as follows:

public final class App {

   
public static void main(String[] args){
         
new Sleeper().start();
   
}

}


2.1.4. The join method

In the above example, the main thread is likely to terminate before the sleeper thread terminates. Let's say you don't want the main thread to terminate before the sleeper thread has terminated. The join method provided by the class Thread allows you to wait for a thread's termination. In fact, the join method blocks the execution of the current thread until the thread it is called upon terminates. In the following example, the main thread waits for the termination of the sleeper thread:

public final class App {

   
public static void main(String[] args){
         
try{
               
Sleeper sleeper = new Sleeper();
                sleeper.start
();
                sleeper.join
();
                System.out.println
("The sleeper thread has terminated");
         
}
         
catch(InterruptedException e){

          }
    }

}


2.1.5 The interrupt method

Thread A can interrupt thread B by calling the method B.interrupt(). If the method B.interrupt() is called while B is blocked (executing sleep, join or wait), then an InterruptedException is thrown (the method wait will be discussed in the tutorial Wait and notify). On the other hand, if the method B.interrupt() is called while B is not blocked, then its interrupted status is set to true. Consequently, the call B.isInterrupted() will return true.

In many situations, threads perform certain operations repeatedly in an infinite loop. In that case, you can use the method interrupt to terminate the thread easily. Here is an example:

public final class B extends Thread {

   
public void run(){
         
try{
               
while(! isInterrupted()){
                     
// perform operations repeatedly, including possible calls to blocking methods like sleep() and join()
                      // ...
                      // ...
               
}
          }
         
catch(InterruptedException e){
               
// do nothing
         
}
    }

}

At each iteration, the while statement tests the interrupted status of B by calling the method isInterrupted. If another thread calls the method B.interrupt, then:
  1. Either B was blocked (in a call to sleep, join or wait). In that case, an InterruptedException is thrown and the catch block is executed. But because the catch block is empty, B simply dies.
  2. Either B was not blocked and the loop is exited at the next iteration as the method isInterrupted returns true. Hence, the thread dies.

You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   2. Concurrency  >   2.1. Threads
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   2. Concurrency  >   2.2. What is synchronization?

Copyright © 2013. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7