JAVA - multithreading three {multithreading state} JAVA starts from the foundation -- 3

Posted by TouranMan on Mon, 03 Jan 2022 14:12:45 +0100

Thread state

  1. new
    1) Thread t= new Thread once the thread object is created, it enters the new state
    2) When the start() method is called, the thread immediately enters the ready state, but it does not mean that the execution is scheduled immediately
  2. Ready state (CPU scheduling operation)
  3. Blocking state (when sleep,wait or synchronous locking is called, the thread enters the blocking state, that is, the code does not execute down. After the blocking event is released, it enters the ready state again and waits for CPU scheduling)
  4. Running state (in this state, the thread body code is actually executed)
  5. Dead (the thread is interrupted or terminated. Once it enters the dead state, it cannot be restarted)

Thread method

setPriority(int newPriority): change thread priority
static void sleep(long millis): hibernates the currently executing thread within the specified milliseconds
void join(): wait for the thread to terminate
static void yield: pauses the currently executing thread object and executes other threads
void interrupt: interrupt the thread. Don't use this method
boolean isAlive(): test whether it is active

stop method_ stop (discard)

The stop method in jdk is not recommended and is discarded

It is recommended to use flag bit mode to stop the thread itself (when flag==false)

//In the tortoise and rabbit race
private boolean gameOver(int steps) {
        //Judge whether there is a winner
        if (winner != null) {
            //There is a winner
            return true;
        } else {
            if (steps >= 100) {
                winner = Thread.currentThread().getName();
                System.out.println(winner + "victory");
                return true;
            } else {
                return false;
            }
        }
    }
    public void run() {
        for (int i = 0; i < 100; i++) {
            //Judge whether to end the game
            boolean flag = gameOver(i + 1);
            if (flag) { //Set flag==true to exit the thread
                break;
            }
            String user = Thread.currentThread().getName();
            if (user == "tortoise") {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else if (user == "rabbit") {
                if (i % 10 == 0) {
                    try {
                        Thread.sleep(400);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println(user + "Run away" + i);
        }
    }

Sleep state_ sleep

Sleep: the number of milliseconds blocked
Exception InterruptedException in sleep
When the sleep time reaches, the thread enters the ready state
sleep can simulate network delay, countdown, etc.
Each object has a lock, and sleep does not release the lock

Analog network delay: the occurrence of amplification problems
For example; In previous cases of ticket grabbing, it is possible for two people to grab a ticket at the same time

Analog countdown

package ThreadControl;


import java.text.SimpleDateFormat;
import java.util.Date;

//Analog countdown
public class ThreadSleep2 {
    private static Date startTime;
    public static Date getTime() {
        startTime = new Date(System.currentTimeMillis());//Get the current system time
        return startTime;
    }
    public static void main(String[] args) throws InterruptedException {
        while (true) {
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(getTime()));
//            if (num <= 0) {
//                break;
//            };
        }
    }
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0) {
                break;
            }
            ;
        }
    }
}

Thread comity_ yield

◆ be courteous to the thread, so that the currently executing thread can be suspended without blocking
◆ change the thread from running state to ready state
◆ let CPU update scheduling, comity may not be successful! Look at CPU mood

package ThreadControl;

//Comity does not necessarily succeed. Look at the CPU
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield, "a").start();
        new Thread(myYield, "b").start();
    }
}
class MyYield implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "Thread starts execution");
        Thread.yield();//Comity
        System.out.println(Thread.currentThread().getName() + "Thread stop execution");
    }
}


Comity success

Thread enforcement_ join

◆ Join merge threads, and execute other threads after the execution of this thread is completed. Other threads are blocked
◆ you can imagine jumping in line

package ThreadControl;

public class TestJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("thread  VIP coming" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        //Main thread
        for (int i = 0; i < 1000; i++) {
            if (i == 200) {
                thread.join();
            }
            System.out.println("main" + i);
        }
    }
}


thread.join(); Jump the queue successfully

Thread state observation_ Thread.State

Thread.State

Thread status. The turn can be in one of the following states
●NEW
A process that has not been started is in this state
●RUNNABLE
The enclosing procedure executed in the Java virtual machine is in this state
●BLOCKED
The thread locked by the Yangjian wait monitor is in this state
●WNAITING
A thread that is waiting for another thread to perform a specific action is in this state.
●TIMED WAITING
The thread that is waiting for another process to execute the action for the specified waiting time is in this state. a
●TERMINATED
The exited thread is in this state
····
A thread can be in a state at a given point in time. These states are virtual states that do not reflect the state of any operating system thread

package ThreadControl;

//Observe the status of the test thread
public class TestState {
    //Observation state
    static Thread.State state;

    static void gets(Thread thr) {
        state = thr.getState();
        System.out.println("Thread status:" + state);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("``````" + i);
            }
        });

        //Before observation start
        gets(thread);

        //After observation start
        thread.start();
        gets(thread);

        while (state != Thread.State.TERMINATED){
            Thread.sleep(500);
            gets(thread);
        }
    }
}

thread priority

◆ Java provides a thread scheduler to monitor all threads that enter the ready state after startup. The thread scheduler determines which thread should be scheduled for execution according to priority.
◆ the priority of threads is expressed in numbers, ranging from 110
-◆ Thread. Min PR|OR|Y=1
-◆Thread. MAX PRIORITY=10
-◆Thread. NORM PRIORITY=5
◆ use the following methods to change or obtain priority
getpriority(). setpriority(int xxx)

Topics: Java Programming Back-end