Thread state switch code

**In fact, the Book java concurrent programming has been read many times and many articles related to multithreading have been skimmed, but if it is not used, it will soon be forgotten again. I thought of a concept and started to operate it again to deepen my cognition**

  • Take a look at the enumeration of Thread states in the source code of thread class. There are six thread states.

` /** * A thread state. A thread can be in one of the following states: * <ul>

 * <li>{[@link](https://my.oschina.net/u/393) #NEW}<br>
 *     A thread that has not yet started is in this state.
      After a thread creates an object, it calls start()Previously, the status was new
 *     </li>
 
 * <li>{[@link](https://my.oschina.net/u/393) #RUNNABLE}<br>
 *     A thread executing in the Java virtual machine is in this state.
       Thread executing in virtual machine, entering RUNABLE State (subdivided into READY(Ready)-Intermediate waiting time segment-as well as RUNNING(In operation)
 *     </li>
 
 * <li>{[@link](https://my.oschina.net/u/393) #BLOCKED}<br>
 *     A thread that is blocked waiting for a monitor lock
 *     is in this state.
      A thread enters the thread blocking state when waiting to acquire the monitor lock, that is, the state of queuing to acquire the lock.
 *     </li>
 
 * <li>{[@link](https://my.oschina.net/u/393) #WAITING}<br>
 *     A thread that is waiting indefinitely for another thread to
 *     perform a particular action is in this state.
       Waiting for other threads to wake up.
 *     </li>
 
 * <li>{[@link](https://my.oschina.net/u/393) #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.
       Wait for other threads to wake up in a certain period of time, and then wake up the thread to acquire the lock again.
 *     </li>
 
 * <li>{@link #TERMINATED}<br>
 *     A thread that has exited is in this state.
       The end state of a thread.
 *     </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;
}`
  • Let's take a look at an example of thread flow

  • And then we'll show it in code

  • NEW (after creating a thread object and before calling start(), the thread state is NEW), after calling start(), it enters RUNABLE, and when the thread execution ends, it enters BLOCKD state

`package com.example.demo.thread;

/**

  • Thread state transition demonstration new runtime */ public class ThreadNewRunable extends Thread {

    private byte[] lock = new byte[0];

    public ThreadNewRunable(byte[] lock) { this.lock = lock; }

    @Override public void run() {

     // doNothing 
    

// synchronized (lock) { // try { //Thread.sleep(1000); / / sleep for ten seconds to prevent the end of too fast // } catch (InterruptedException e) { // e.printStackTrace(); // } // } }

public static void main(String[] args) throws InterruptedException {


    byte[] lock = new byte[0];
    ThreadNewRunable threadNewRunable = new ThreadNewRunable(lock);
    System.out.println("threadStatu-new : " + threadNewRunable.getState());

    threadNewRunable.start();
    System.out.println("threadStatus-start: " + threadNewRunable.getState());

    ThreadNewRunable threadNewRunable1 = new ThreadNewRunable(lock);
    threadNewRunable1.start();


    Thread.sleep(1000);

    System.out.println("threadStatu1-blocked : " + threadNewRunable1.getState());
}

}

`

  • Output results

threadStatu-new : NEW threadStatus-start: RUNNABLE threadStatu1-blocked : TERMINATED

  • BLOCKED when a thread is waiting to acquire a lock, synchronized block or synchronized method, the thread will enter a BLOCKED state

`package com.example.demo.thread;

public class ThreadBlocked extends Thread {

private byte[] lock = new byte[0];

public ThreadBlocked(byte[] lock) {
    this.lock = lock;
}

@Override
public void run() {

    synchronized (lock) {
        try {
            Thread.sleep(10000);// Sleep for 10 seconds to prevent the end of too fast
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args) throws InterruptedException {
    byte[] lock = new byte[0];
    ThreadBlocked threadBlocked = new ThreadBlocked(lock);
    threadBlocked.start();
    ThreadBlocked threadBlocked1 = new ThreadBlocked(lock);
    threadBlocked1.start();
    Thread.sleep(1000);
    System.out.println("threadBlocked1-blocked : " + threadBlocked1.getState());
}

}

`

  • output

threadBlocked1-blocked : BLOCKED

  • WAITING (when Object.wait(); Thread.join(); LockSupport.park(); is executed, the thread will be counted as WAITING)

  • Object.wait()

`package com.example.demo.thread;

public class ThreadWaitingObjectWait extends Thread {

private byte[] lock = new byte[0];

public ThreadWaitingObjectWait(byte[] lock) {
    this.lock = lock;
}

@Override
public void run() {

    synchronized (lock) {
        try {
            lock.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args) throws InterruptedException {
    byte[] lock = new byte[0];
    ThreadWaitingObjectWait waitingObjectWait = new ThreadWaitingObjectWait(lock);
    waitingObjectWait.start();
    Thread.sleep(100);

    System.out.println("waitingObjectWait wait.start(): " + waitingObjectWait.getState());

    synchronized (lock) {
        lock.notify();
    }
    Thread.sleep(100);
    System.out.println("waitingObjectWait lock.notify() :" + waitingObjectWait.getState());
}

} `

  • output

waitingObjectWait wait.start(): WAITING waitingObjectWait lock.notify() :TERMINATED

  • LockSupport.park()

`package com.example.demo.thread;

import java.util.concurrent.locks.LockSupport;

public class ThreadWaitingPark extends Thread {

private byte[] lock = new byte[0];

public ThreadWaitingPark(byte[] lock) {
    this.lock = lock;
}

@Override
public void run() {

        // The following three can make the thread enter the waiting state

// Object.wait(); // Thread.join();; LockSupport.park();

}

public static void main(String[] args) throws InterruptedException {
    byte[] lock = new byte[0];
    ThreadWaitingPark threadWaitingPark = new ThreadWaitingPark(lock);
    threadWaitingPark.start();
    Thread.sleep(1000);
    System.out.println("threadWaiting-Waiting-when LockSupport.park() : " + threadWaitingPark.getState());
    LockSupport.unpark(threadWaitingPark);
    Thread.sleep(1000);
    System.out.println("threadWaiting-Waiting-when LockSupport.unpark(thread)  : " + threadWaitingPark.getState());


}

} `

  • output

threadWaiting-Waiting-when LockSupport.park() : WAITING threadWaiting-Waiting-when LockSupport.unpark(thread) : TERMINATED

  • Thread.join()

`package com.example.demo.thread;

import org.jetbrains.annotations.NotNull;

public class ThreadWaitingThreadJoin extends Thread {

private Thread thread = new Thread();

public ThreadWaitingThreadJoin(Thread thread) {
    this.thread = thread;
}

@Override
public void run() {
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws InterruptedException {
    byte[] lock = new byte[0];
    ThreadNewRunable threadNewRunable = new ThreadNewRunable(lock);
    threadNewRunable.start();
    ThreadWaitingThreadJoin threadWaitingThreadJoin = new ThreadWaitingThreadJoin(threadNewRunable);
    threadWaitingThreadJoin.start();
    Thread.sleep(100);
    System.out.println("threadWaitingThreadJoin.join() : " + threadWaitingThreadJoin.getState());
}

} `

  • output

threadWaitingThreadJoin.join() : TERMINATED

  • Timewaiting (WAITING waits as long as there is no thread waking up, and timewaiting wakes up the thread to acquire the lock after the WAITING time is exceeded)

When executed Thread.sleep(long); Object.wait(long); Thread.join(long); LockSupport.parkNanos(); LockSupport.parkUntil(); The thread will enter the delay waiting state.

  • Thread.sleep(long)

`package com.example.demo.thread;

public class ThreadTimedWaitingThreadSleep extends Thread {

private byte[] lock = new byte[0];

public ThreadTimedWaitingThreadSleep(byte[] lock) {
    this.lock = lock;
}

@Override
public void run() {
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws InterruptedException {
    byte[] lock = new byte[0];
    ThreadTimedWaitingThreadSleep timedWaitingThreadSleep = new ThreadTimedWaitingThreadSleep(lock);
    timedWaitingThreadSleep.start();
    Thread.sleep(100);
    System.out.println("timedWaitingThreadSleep Thread.sleep(long) : " + timedWaitingThreadSleep.getState());
}

} `

  • output

timedWaitingThreadSleep Thread.sleep(long) : TIMED_WAITING

  • Object.wait(long)

`package com.example.demo.thread;

public class ThreadTimedWaitingObjectWait extends Thread { private byte[] lock = new byte[0];

public ThreadTimedWaitingObjectWait(byte[] lock) {
    this.lock = lock;
}

@Override
public void run() {


    synchronized (lock) {
        // Other causes the thread to enter timedWaiting
        // Thread.join(long)
        //LockSupport.parkNanos()
        //LockSupport.parkUntil()
        try {
            lock.wait(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args) throws InterruptedException {
    byte[] lock = new byte[0];
    ThreadTimedWaitingObjectWait timedWaitingObjectWait = new ThreadTimedWaitingObjectWait(lock);
    timedWaitingObjectWait.start();
    Thread.sleep(100);

    System.out.println("timedWaitingObjectWait wait.start(): " + timedWaitingObjectWait.getState());

    Thread.sleep(2000);
    System.out.println("timedWaitingObjectWait after sleep(20000) :" + timedWaitingObjectWait.getState());
}

} `

  • output

timedWaitingObjectWait wait.start(): TIMED_WAITING

  • The source code is in the road package of the following project. You need to take it yourself

Source warehouse address

Tags: Programming Java

Posted on Sun, 10 May 2020 10:38:46 -0400 by JeremyCanada26