Explain several states of Java threads in detail

Posted by aks.it on Mon, 17 Jan 2022 01:31:18 +0100

The following is the built-in enumeration of states in the Thread class source code, which lists several states of Java threads:

/**
 * A thread state.  A thread can be in one of the following states:
 * <ul>
 * <li>{@link #NEW}<br>
 *     A thread that has not yet started is in this state.
 *     </li>
 * <li>{@link #RUNNABLE}<br>
 *     A thread executing in the Java virtual machine is in this state.
 *     </li>
 * <li>{@link #BLOCKED}<br>
 *     A thread that is blocked waiting for a monitor lock
 *     is in this state.
 *     </li>
 * <li>{@link #WAITING}<br>
 *     A thread that is waiting indefinitely for another thread to
 *     perform a particular action is in this state.
 *     </li>
 * <li>{@link #TIMED_WAITING}<br>
 *     A thread that is waiting for another thread to perform an action
 *     for up to a specified waiting time is in this state.
 *     </li>
 * <li>{@link #TERMINATED}<br>
 *     A thread that has exited is in this state.
 *     </li>
 * </ul>
 *
 * <p>
 * A thread can be in only one state at a given point in time.
 * These states are virtual machine states which do not reflect
 * any operating system thread states.
 *
 * @since   1.5
 * @see #getState
 */
public enum State {
    /**
     * Thread state for a thread which has not yet started.
     */
    NEW,

    /**
     * Thread state for a runnable thread.  A thread in the runnable
     * state is executing in the Java virtual machine but it may
     * be waiting for other resources from the operating system
     * such as processor.
     */
    RUNNABLE,

    /**
     * Thread state for a thread blocked waiting for a monitor lock.
     * A thread in the blocked state is waiting for a monitor lock
     * to enter a synchronized block/method or
     * reenter a synchronized block/method after calling
     * {@link Object#wait() Object.wait}.
     */
    BLOCKED,

    /**
     * Thread state for a waiting thread.
     * A thread is in the waiting state due to calling one of the
     * following methods:
     * <ul>
     *   <li>{@link Object#wait() Object.wait} with no timeout</li>
     *   <li>{@link #join() Thread.join} with no timeout</li>
     *   <li>{@link LockSupport#park() LockSupport.park}</li>
     * </ul>
     *
     * <p>A thread in the waiting state is waiting for another thread to
     * perform a particular action.
     *
     * For example, a thread that has called <tt>Object.wait()</tt>
     * on an object is waiting for another thread to call
     * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
     * that object. A thread that has called <tt>Thread.join()</tt>
     * is waiting for a specified thread to terminate.
     */
    WAITING,

    /**
     * Thread state for a waiting thread with a specified waiting time.
     * A thread is in the timed waiting state due to calling one of
     * the following methods with a specified positive waiting time:
     * <ul>
     *   <li>{@link #sleep Thread.sleep}</li>
     *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
     *   <li>{@link #join(long) Thread.join} with timeout</li>
     *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
     *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
     * </ul>
     */
    TIMED_WAITING,

    /**
     * Thread state for a terminated thread.
     * The thread has completed execution.
     */
    TERMINATED;
}

1 what is thread [source: Baidu Encyclopedia]

Thread (English: thread) is the smallest unit that the operating system can schedule operations. It is included in the process, yes process The actual operating unit in. A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel. In Unix System V and SunOS, it is also called lightweight processes, but lightweight processes refer more to kernel thread s and user thread s to threads.

Thread is the basic unit of independent scheduling and dispatching. Threads can be kernel threads scheduled for the operating system kernel, such as Win32 threads; User threads scheduled by user processes, such as POSIX Thread on Linux platform; Alternatively, the kernel and user processes, such as Windows 7 threads, perform mixed scheduling.

Multiple threads in the same process will share all system resources in the process, such as virtual address space, file descriptor, signal processing and so on. However, multiple threads in the same process have their own call stack, their own register context, and their own thread local storage.

A process can have many threads, and each thread performs different tasks in parallel.

The benefits of using multithreaded programming on multi-core or multi CPUs, or CPUs that support hyper threading, are obvious, that is, it improves the execution throughput of the program. On a single CPU and single core computer, using multithreading technology, you can also separate the often blocked part in the process responsible for I/O processing and human-computer interaction from the part of intensive computing, and write a special workhorse thread to perform intensive computing, so as to improve the execution efficiency of the program.

2 several states of thread

A thread can only be in one state at a given point in time. These states are virtual machine states that do not reflect the state of any operating system threads.

NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED

3 Introduction

3.1 NEW

The thread state of a thread that has not been started.

When a Thread object is generated, a new Thread is generated. When the Thread is in the "new Thread" state, it is only an empty Thread object, which has not been allocated to system resources. Therefore, it can only be started or terminated. Any other operation will throw an exception. For example, if a Thread is in the new Thread state after calling the new method and before calling the start method, you can call the start and stop methods.

Trigger mode:

Thread thread = new Thread();

3.2 RUNNABLE

The thread state of the runnable thread. A runnable thread is executing in the Java virtual machine, but it may be waiting for other resources from the operating system, such as the processor.

The start () method generates the resources necessary to run the thread, schedules the thread execution, and calls the thread's run () method. At this time, the thread is in a Runnable state. This state is not called running state because the thread at this time does not always occupy the processor. Especially for a PC with only one processor, only one running thread can occupy the processor at any time. Java implements the sharing of processors by multithreading through scheduling. Note that if the thread is in the Runnable state, it may not be running because there are priority and scheduling problems.

Trigger mode:

Thread thread = new Thread();
thread.start();
or
thread.run();

What is the difference between the start() and run() methods?

Turn to the source code again:

/**
 * Causes this thread to begin execution; the Java Virtual Machine
 * calls the <code>run</code> method of this thread.
 * <p>
 * Make this thread start execution; The Java virtual machine calls the run method of the thread.
 * The result is that two threads are running concurrently: the
 * current thread (which returns from the call to the
 * <code>start</code> method) and the other thread (which executes its
 * <code>run</code> method).
 * The result is that two threads run simultaneously: the current thread (returned from calling the start method) and another thread (executing its run method).
 * <p>
 * It is never legal to start a thread more than once.
 * In particular, a thread may not be restarted once it has completed
 * execution.
 * It is illegal for a thread to start more than once. In particular, threads may not restart after execution.
 */
public synchronized void start() {
    if (threadStatus != 0)
        throw new IllegalThreadStateException();
    /* Notifies the group that the thread is about to start so that it can be added to the group's thread list, and the group's non start count can be reduced. */
    group.add(this);
    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

/**
 * If this thread was constructed using a separate
 * <code>Runnable</code> run object, then that
 * <code>Runnable</code> object's <code>run</code> method is called;
 * otherwise, this method does nothing and returns.
 * If the thread is constructed with a separate Runnable object, the run method of the Runnable object is called; Otherwise, this method does not execute 
 * Do anything and return.
 * <p>
 * Subclasses of <code>Thread</code> should override this method.
 * Subclasses of Thread should override this method.  
 */
@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

From the source code, we can know:

  • When the start() method is called, it is put into the thread group for asynchronous execution, not necessarily direct execution
  • Call the run() method for synchronous execution, that is, direct execution

3.3 BLOCKED

The thread state of a thread that is blocked waiting for a monitor lock. The blocked thread is waiting for the monitor lock to enter a synchronized block / method, or is calling object After wait, re-enter a synchronized block / method.

Trigger mechanism:

Object.wait();
thread.interrupt()

3.4 WAITING

A waiting thread is waiting for another thread to perform a specific action.

Trigger mechanism:

Object.wait();
or
thread.join()
or(Lock support)
LockSupport.park()

Cancel wait:

Object.notify() 
or
Object.notifyAll()

3.5 TIMED_WAITING

The thread state of the waiting thread with the specified waiting time. The thread is in a timed wait state because one of the following methods is called and the waiting time is specified

Trigger mechanism:

Thread.sleep()
or
Object.wait()
or
Thread.join()
or
LockSupport.parkNanos
 or
LockSupport.parkUntil

3.6 TERMINATED

The thread state of the terminating thread. The thread has completed execution.

Trigger mechanism:

thread.stop();

Topics: Java Multithreading