Multi-tasking.

Thread Methods in Java with Example

  • Java
  • 4 mins read

In this tutorial, you will learn about the thread methods in Java with example.

The Thread class provides many helpful methods for control. As a quick overview, here are some of the methods used most often:

start()

The start() method starts the execution of a thread and executes the body defined in its run() method, or the run() method of the Runnable passed to the constructor. Program control returns immediately, with the new thread executing run() concurrently.

interrupt()

The interrupt() method sets a thread's interrupt status. It also causes a thread to stop being blocked if it is waiting on a monitor lock, waiting for I/O on a java.nio-channels.Channel, or blocked in a java.nio.channels.Selector. If a thread is waiting on a non-channel oriented I/O operation, interrupt() does not unblock the operation.

join()

The join() method causes a thread to wait for another thread to finish. You would call this method for another thread, not for the thread in which the code is executing.

NOTE

The thread class also contains the suspend(), resume(), and stop() methods. Their use has been deprecated, and you should avoid using them. They were deprecated because they can cause the system to become unstable.

Some thread operations, listed next, only work on the currently executing thread. In other words, the methods are static:

currentThread()

This method returns a reference to the thread currently executing.

dumpStack()

The dumpStack() is a useful debugging method for dumping the stack of the current thread on demand. The stock is a call trace of methods, getting the thread to its current execution point.

sleep(long milliseconds) and sleep(long milliseconds, long nanoseconds)

These two methods cause the runtime environment to put the currently executing thread to sleep for the specified period. This call must be placed within a try-catch block because an Interrupted-Exception may be thrown if the thread is interrupted with interrupt(). The thread does not automatically start after the specified sleep period, but it will be runnable. Using the nanoseconds version of this method tends to be overkill, but it is available.

yield()

The yield() method causes the executing thread to stop temporarily and give the thread scheduler a chance to let another thread run. If there is nothing else to run, the thread will continue executing without a context swap.

The following example shows some of these thread-control methods at work. In this example, the main thread creates two threads and then waits for the first thread to finish by calling the first thread's join() method.

The first thread calls the sleep() method to be asleep for 10 seconds. Meanwhile, the second thread calls its own wait() method to suspend itself until the main thread calls the notify() method of the suspended thread. After the first thread comes to an end, the main thread method, and waits until the second thread comes to an end as well by calling the second thread's join() method.

Example: Thread Methods in Java

// MethodTest.java
public class MethodTest {

    static class FirstThread extends Thread {

        public void run() {
            try {
                System.out.println("   Frist thread starts running.");
                sleep(10000);
                System.out.println("   First thread finishes running.");
            } catch (InterruptedException e) {
                System.err.println("Error in thread: " + e);
            }
        }
    }

    static class SecondRunnable implements Runnable {

        public synchronized void run() {
            try {
                System.out.println("   Second thread starts running.");
                System.out.println("   Second thread suspends itself.");
                wait();
                System.out.println("   Second thread runs again and finishes.");

            } catch (InterruptedException e) {
                System.err.println("Error in runnable: " + e);
            }
        }
    }

    public static void main(String args[]) {
        Thread first = new FirstThread();
        Runnable secondRunnable = new SecondRunnable();
        Thread second = new Thread(secondRunnable);
        first.start();
        second.start();
        try {
            System.out.println("Waiting for first thread to finish...");
            first.join();
            System.out.println("It's a long wait!");
            System.out.println("Waking up second thread...");
            synchronized (secondRunnable) {
                secondRunnable.notify();
            }
            System.out.println("Waiting for second thread to finish...");
            second.join();

        } catch (InterruptedException e) {
            System.out.println("Error in main: " + e);
        }
        System.out.println("I am ready to finish too.");
    }
}

Test

java MethodTest

Output

Waiting for first thread to finish...
   Second thread starts running.
   Second thread suspends itself.
   Frist thread starts running.
   First thread finishes running.
It's a long wait!
Waking up second thread...
Waiting for second thread to finish...
   Second thread runs again and finishes.
I am ready to finish too.

See also: