Java Threads Tutorial

Multithreading refers to two or more tasks executing concurrently within a single program. A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A Java program can have many threads, and these threads can run concurrently, either asynchronously or synchronously.

Multithreading has several advantages over Multiprocessing such as;

  • Threads are lightweight compared to processes
  • Threads share the same address space and therefore can share both data and code
  • Context switching between threads is usually less expensive than between processes
  • Cost of thread intercommunication is relatively low that that of process intercommunication
  • Threads allow different tasks to be performed concurrently.

The following figure shows the methods that are members of the Object and Thread Class.

Thread Creation

There are two ways to create thread in java;

  • Implement the Runnable interface (java.lang.Runnable)
  • By Extending the Thread class (java.lang.Thread)

Implementing the Runnable Interface

The Runnable Interface Signature

public interface Runnable {

void run();

}

One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run() method into our class which is the only method that needs to be implemented. The run() method contains the logic of the thread.

The procedure for creating threads based on the Runnable interface is as follows:

1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object.

2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method.

3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned.

4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception.

Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.

class RunnableThread implements Runnable {


Thread runner;
public RunnableThread() {
}
public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}

public class RunnableExample {

public static void main(String[] args) {
Thread thread1 = new Thread(new RunnableThread(), “thread1″);
Thread thread2 = new Thread(new RunnableThread(), “thread2″);
RunnableThread thread3 = new RunnableThread(”thread3″);
//Start the threads
thread1.start();
thread2.start();
try {
//delay for one second
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}

Output

thread3
Thread[thread1,5,main]
Thread[thread2,5,main]
Thread[thread3,5,main]
Thread[main,5,main]private


This approach of creating a thread by implementing the Runnable Interface must be used whenever the class being used to instantiate the thread object is required to extend some other class.

Extending Thread Class

The procedure for creating threads based on extending the Thread is as follows:

1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.

2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call.

3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.

Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.

class XThread extends Thread {


XThread() {
}
XThread(String threadName) {
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}

public class ThreadExample {

public static void main(String[] args) {
Thread thread1 = new Thread(new XThread(), “thread1″);
Thread thread2 = new Thread(new XThread(), “thread2″);
// The below 2 threads are assigned default names
Thread thread3 = new XThread();
Thread thread4 = new XThread();
Thread thread5 = new XThread(”thread5″);
//Start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
//The sleep() method is invoked on the main thread to cause a one second delay.
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}

Output

Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]


When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:

  • Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface
    has this option.
  • A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.

An example of an anonymous class below shows how to create a thread and start it:

( new Thread() {

public void run() {

for(;;) System.out.println(”Stop the world!”);

}

}

).start();



Thread Synchronization

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time.

In non synchronized multithreaded application, it is possible for one thread to modify a shared object while

another thread is in the process of using or updating the object’s value. Synchronization prevents such type
of data corruption which may otherwise lead to dirty reads and significant errors.
Generally critical sections of the code are usually marked with synchronized keyword.

Examples of using Thread Synchronization is in “The Producer/Consumer Model”.

Locks are used to synchronize access to a shared resource. A lock can be associated with a shared resource.
Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code.
At any given time, at most only one thread can hold the lock and thereby have access to the shared resource.
A lock thus implements mutual exclusion.

The object lock mechanism enforces the following rules of synchronization:

  • A thread must acquire the object lock associated with a shared resource, before it can enter the shared
    resource. The runtime system ensures that no other thread can enter a shared resource if another thread
    already holds the object lock associated with the shared resource. If a thread cannot immediately acquire
    the object lock, it is blocked, that is, it must wait for the lock to become available.
  • When a thread exits a shared resource, the runtime system ensures that the object lock is also relinquished.
    If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain access
    to the shared resource.
  • Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually a
    lock on the java.lang.Class object associated with the class. Given a class A, the reference A.class
    denotes this unique Class object. The class lock can be used in much the same way as an object lock to
    implement mutual exclusion.

    There can be 2 ways through which synchronized can be implemented in Java:

    • synchronized methods
    • synchronized blocks

    Synchronized statements are same as synchronized methods. A synchronized statement can only be
    executed after a thread has acquired the lock on the object/class referenced in the synchronized statement.

    Synchronized Methods

    Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. .If the lock is already held by another thread, the calling thread waits. A thread relinquishes the lock simply by returning from the synchronized method, allowing the next thread waiting for this lock to proceed. Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. This is called a race condition. It occurs when two or more threads simultaneously update the same value, and as a consequence, leave the value in an undefined or inconsistent state. While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait until it gets the lock. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread.

    Below is an example shows how synchronized methods and object locks are used to coordinate access to a common object by multiple threads. If the ’synchronized’ keyword is removed, the message is displayed in random fashion.

    public class SyncMethodsExample extends Thread {
    

    static String[] msg = { “Beginner”, “java”, “tutorial,”, “.,”, “com”,
    “is”, “the”, “best” };
    public SyncMethodsExample(String id) {
    super(id);
    }
    public static void main(String[] args) {
    SyncMethodsExample thread1 = new SyncMethodsExample(”thread1: “);
    SyncMethodsExample thread2 = new SyncMethodsExample(”thread2: “);
    thread1.start();
    thread2.start();
    boolean t1IsAlive = true;
    boolean t2IsAlive = true;
    do {
    if (t1IsAlive && !thread1.isAlive()) {
    t1IsAlive = false;
    System.out.println(”t1 is dead.”);
    }

    if (t2IsAlive && !thread2.isAlive()) {
    t2IsAlive = false;
    System.out.println(”t2 is dead.”);
    }
    } while (t1IsAlive || t2IsAlive);
    }
    void randomWait() {
    try {
    Thread.currentThread().sleep((long) (3000 * Math.random()));
    } catch (InterruptedException e) {
    System.out.println(”Interrupted!”);
    }
    }
    public synchronized void run() {
    SynchronizedOutput.displayList(getName(), msg);
    }
    }

    class SynchronizedOutput {

    // if the ’synchronized’ keyword is removed, the message
    // is displayed in random fashion
    public static synchronized void displayList(String name, String list[]) {
    for (int i = 0; i < list.length; i++) {
    SyncMethodsExample t = (SyncMethodsExample) Thread
    .currentThread();
    t.randomWait();
    System.out.println(name + list[i]);
    }
    }
    }

    Output

    thread1: Beginner
    thread1: java
    thread1: tutorial,
    thread1: .,
    thread1: com
    thread1: is
    thread1: the
    thread1: best
    t1 is dead.
    thread2: Beginner
    thread2: java
    thread2: tutorial,
    thread2: .,
    thread2: com
    thread2: is
    thread2: the
    thread2: best
    t2 is dead.

    Download Synchronized Methods Thread Program Example

    Class Locks

    Synchronized Blocks

    Static methods synchronize on the class lock. Acquiring and relinquishing a class lock by a thread in order to execute a static synchronized method, proceeds analogous to that of an object lock for a synchronized instance method. A thread acquires the class lock before it can proceed with the execution of any static synchronized method in the class, blocking other threads wishing to execute any such methods in the same class. This, of course, does not apply to static, non-synchronized methods, which can be invoked at any time. Synchronization of static methods in a class is independent from the synchronization of instance methods on objects of the class. A subclass decides whether the new definition of an inherited synchronized method will remain synchronized in the subclass.The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.
    The general form of the synchronized block is as follows:

    synchronized () {

    }

    A compile-time error occurs if the expression produces a value of any primitive type. If execution of the block completes normally, then the lock is released. If execution of the block completes abruptly, then the lock is released.
    A thread can hold more than one lock at a time. Synchronized statements can be nested. Synchronized statements with identical expressions can be nested. The expression must evaluate to a non-null reference value, otherwise, a NullPointerException is thrown.

    The code block is usually related to the object on which the synchronization is being done. This is the case with synchronized methods, where the execution of the method is synchronized on the lock of the current object:

    public Object method() {
    synchronized (this) { // Synchronized block on current object
    // method block
    }
    }

    Once a thread has entered the code block after acquiring the lock on the specified object, no other thread will be able to execute the code block, or any other code requiring the same object lock, until the lock is relinquished. This happens when the execution of the code block completes normally or an uncaught exception is thrown.

    Object specification in the synchronized statement is mandatory. A class can choose to synchronize the execution of a part of a method, by using the this reference and putting the relevant part of the method in the synchronized block. The braces of the block cannot be left out, even if the code block has just one statement.

    class SmartClient {
    BankAccount account;
    // …
    public void updateTransaction() {
    synchronized (account) { // (1) synchronized block
    account.update(); // (2)
    }
    }
    }

    In the previous example, the code at (2) in the synchronized block at (1) is synchronized on the BankAccount object. If several threads were to concurrently execute the method updateTransaction() on an object of SmartClient, the statement at (2) would be executed by one thread at a time, only after synchronizing on the BankAccount object associated with this particular instance of SmartClient.

    Inner classes can access data in their enclosing context. An inner object might need to synchronize on its associated outer object, in order to ensure integrity of data in the latter. This is illustrated in the following code where the synchronized block at (5) uses the special form of the this reference to synchronize on the outer object associated with an object of the inner class. This setup ensures that a thread executing the method setPi() in an inner object can only access the private double field myPi at (2) in the synchronized block at (5), by first acquiring the lock on the associated outer object. If another thread has the lock of the associated outer object, the thread in the inner object has to wait for the lock to be relinquished before it can proceed with the execution of the synchronized block at (5). However, synchronizing on an inner object and on its associated outer object are independent of each other, unless enforced explicitly, as in the following code:

    class Outer { // (1) Top-level Class
    private double myPi; // (2)
    protected class Inner { // (3) Non-static member Class
    public void setPi() { // (4)
    synchronized(Outer.this) { // (5) Synchronized block on outer object
    myPi = Math.PI; // (6)
    }
    }
    }
    }

    Below example shows how synchronized block and object locks are used to coordinate access to shared objects by multiple threads.

    public class SyncBlockExample extends Thread {
    

    static String[] msg = { “Beginner”, “java”, “tutorial,”, “.,”, “com”,
    “is”, “the”, “best” };
    public SyncBlockExample(String id) {
    super(id);
    }
    public static void main(String[] args) {
    SyncBlockExample thread1 = new SyncBlockExample(”thread1: “);
    SyncBlockExample thread2 = new SyncBlockExample(”thread2: “);
    thread1.start();
    thread2.start();
    boolean t1IsAlive = true;
    boolean t2IsAlive = true;
    do {
    if (t1IsAlive && !thread1.isAlive()) {
    t1IsAlive = false;
    System.out.println(”t1 is dead.”);
    }
    if (t2IsAlive && !thread2.isAlive()) {
    t2IsAlive = false;
    System.out.println(”t2 is dead.”);
    }
    } while (t1IsAlive || t2IsAlive);
    }
    void randomWait() {
    try {
    Thread.currentThread().sleep((long) (3000 * Math.random()));
    } catch (InterruptedException e) {
    System.out.println(”Interrupted!”);
    }
    }
    public void run() {
    synchronized (System.out) {
    for (int i = 0; i < msg.length; i++) {
    randomWait();
    System.out.println(getName() + msg[i]);
    }
    }
    }
    }

    Output

    thread1: Beginner
    thread1: java
    thread1: tutorial,
    thread1: .,
    thread1: com
    thread1: is
    thread1: the
    thread1: best
    t1 is dead.
    thread2: Beginner
    thread2: java
    thread2: tutorial,
    thread2: .,
    thread2: com
    thread2: is
    thread2: the
    thread2: best
    t2 is dead.

    Synchronized blocks can also be specified on a class lock:

    synchronized (.class) { }

    The block synchronizes on the lock of the object denoted by the reference .class. A static synchronized method
    classAction() in class A is equivalent to the following declaration:

    static void classAction() {

    synchronized (A.class) { // Synchronized block on class A

    // …

    }

    }

    In summary, a thread can hold a lock on an object

    • by executing a synchronized instance method of the object
    • by executing the body of a synchronized block that synchronizes on the object
    • by executing a synchronized static method of a class