This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

Thread State Overview

The complete process of a thread from birth to death:

When a thread is created and started, it is neither in the execution state as soon as it is started nor always in the execution state. How many states are there in the lifetime of a thread? There are six Thread states given in the API in the enumeration java.lang.thread. State:

Thread state Condition that causes the state to occur
NEW (NEW) The thread has just been created, but has not been started. The start method has not been called. MyThread t = new MyThread has only thread objects and no thread characteristics.
Runnable The state in which threads can run in the Java VIRTUAL machine may or may not be running their own code, depending on the operating system processor. T.start () is called: ready
Blocked. When a thread attempts to acquire an object lock that is held by another thread, the thread enters the Blocked state. When the thread holds the lock, the thread becomes Runnable.
Waiting(for no time) A thread is in Waiting state when it is Waiting for another thread to perform an action. This state cannot be woken up automatically. It must wait for another thread to call notify or notifyAll to wake up.
Timed Waiting In the waiting state, several methods have timeout parameters. Calling them will enter the Timed Waiting state. This state remains until the timeout expires or a wake up notification is received. Common methods with timeout parameters are thread. sleep and Object.wait.
Teminated(terminated) Death occurs because the run method exits normally, or because an exception that did not catch terminates the run method.

Sleep sleep method

One of the states is called timing wait, which can be demonstrated using the methods of the Thread class. Public static void sleep(long time) Causes the current thread to go to sleep

// The main thread sleeps for 1 second before resuming execution
public class Test{
  public static void main(String[] args){
    for(int i = 1; i<=5; i++){ Thread.sleep(1000);
        System.out.println(i)   
    } 
  }
}
Copy the code
Wait and wake up

Public void wait() : This method must lock the object call.

public class Demo1_wait {
    public static void main(String[] args) throws InterruptedException {
	   // Step 1: The child thread starts and enters the infinite wait state. It is not woken up and cannot continue running.
        new Thread(() -> {
            try {

                System.out.println("begin wait ....");
                synchronized ("") {
                    "".wait();
                }
                System.out.println("over");
            } catch (Exception e) {
            }
        }).start();
    }
Copy the code

Public void notify() : This method must be called on the lock object.

public class Demo2_notify {
    public static void main(String[] args) throws InterruptedException {
	   // Step 1: The child thread starts and enters the infinite wait state. It is not woken up and cannot continue running.
        new Thread(() -> {
            try {

                System.out.println("begin wait ....");
                synchronized ("") {
                    "".wait();
                }
                System.out.println("over");
            } catch (Exception e) {
            }
        }).start();

        // Step 2: After 3 seconds, notify is executed to wake up the wait thread.
        Thread.sleep(3000);
        new Thread(() -> {
            try {
                synchronized ("") {
                    System.out.println("Wake up");
                    "".notify(); }}catch(Exception e) { } }).start(); }}Copy the code
A small example of waiting to wake up

Define a set, bun shop thread to complete the production of steamed stuffed bun, steamed stuffed bun added to the set; The foodie thread completes the purchase of the bun and the bun is removed from the collection.

  1. When the bun is not available (the bun state is false), the foodie thread waits.
  2. The bun shop thread produces the bun (i.e. the bun status is true) and notifies the foodie thread (unwaits the foodie).
public class BaoZiPu extends Thread{
    private List<String> list ;
    public BaoZiPu(String name,ArrayList<String> list){
        super(name);
        this.list = list;
    }
    @Override
    public void run(a) {
        	int i = 0; 
            while(true) {//list as the lock object
                    synchronized (list){
                        if(list.size()>0) {// The thread holding the element enters the wait state
                            try {
                                list.wait();
                            } catch(InterruptedException e) { e.printStackTrace(); }}// If the thread does not enter the wait state, there are no elements in the collection
                        // Add elements to the collection
                        list.add("Steamed buns"+i++);
                        System.out.println(list);
                        // There are already elements in the collection
                        list.notify();
                    }
                }
            }
    }
}
Copy the code
public class ChiHuo extends Thread {

    private List<String> list ;
    public ChiHuo(String name,ArrayList<String> list){
        super(name);
        this.list = list;
    }

    @Override
    public void run(a) {
 			// Write an infinite loop to see the effect
                while(true) {// Because the same collection list is used as the lock object
                    synchronized (list){
                        If there is no element in the collection, the thread that fetched the element enters the wait state
                        if(list.size()==0) {try {
                                list.wait();
                            } catch(InterruptedException e) { e.printStackTrace(); }}// If there are elements in the collection, the thread fetching the element retrieves the element (delete)
                        list.remove(0);
                        There are no elements in the collection
                        System.out.println(list);
                        // If there are no more elements in the collection, wake up the adding thread to add elements to the collection
                        list.notify();
                    }
                }
            }
    }
}
Copy the code
public class Demo {
    public static void main(String[] args) {
        // Wait for the wake up case
        List<String> list = new ArrayList<>();
        // Create a thread object
         BaoZiPu bzp = new BaoZiPu("Bun shop",list);
        ChiHuo ch = new ChiHuo("Version",list);
        // Start the threadbzp.start(); ch.start(); }}Copy the code