Multithreading-Thread State-Intermediate Evolution 04

Multithreading-Thread State-Intermediate Evolution 04

5 states of thread

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-FWyxsXWd-1600053055673)(/Users/chenxiwen/Library/Application Support/typora-user-images/image-20200907092936502 .png)]

method

setPriority: change thread priority

sleep

join: wait for the thread to terminate

yield: pause the current thread and let other threads go first

isAlive: test whether the thread is alive

Thread stop

Use flags to let the thread stop by itself

It is not recommended to use stop() provided by JDK

It is recommended to use a flag to plant variables. When flag=false, the thread is terminated.

public class TestStop implements Runnable{
    
    

    private boolean flag = true;

    @Override
    public void run() {
    
    
        int i = 0;
        while (flag) {
    
    
            System.out.println("线程"+i++);
        }
    }

    public void stop() {
    
    
        this.flag=false;
    }

    public static void main(String[] args) {
    
    
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 1000; i++) {
    
    
            System.out.println("main"+i);
            if (i == 900) {
    
    
                testStop.stop();
                System.out.println("stop");
            }
        }

    }
}

Thread sleep

sleep (time) specifies the number of milliseconds that the current thread is blocked

Sleep has an exception InterruptedException

The thread enters the ready state after the sleep time is reached

sleep can simulate network delay, countdown, etc.

Every object has a lock, sleep will not release the lock

public static void main(String[] args) {
    try {
        tendown();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    //打印当前系统时间
    Date startTime = new Date(System.currentTimeMillis());
    while (true) {
        try {
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
            startTime = new Date(System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public static void tendown() throws InterruptedException {
    int num =10;
    while (true) {
        Thread.sleep(1000);
        System.out.println(num--);
        if (num < 0) {
            break;
        }
    }
}

Thread courtesy Yield

Polite thread, let the currently executing thread pause, but not block

Turn the thread from the running state to the ready state

Let CPU reschedule, politeness may not be successful, depending on CPU mood

Thread jump join

Join merge threads, wait until the execution of the second thread is completed, and then execute other threads, other threads are blocked

Can be imagined as jumping in line

//join,插队
public class TestJoin implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("vip来了"+i);
        }
    }

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

        for (int i = 0; i < 1000; i++) {
            if (i == 20) {
                thred.join();
            }
            System.out.println("main"+i);
        }
    }
}

Thread state observation

Thread State

Thread state: the thread can be in one of the following states

  • NEW
    Threads that have not been started are in this state.
  • RUNNABLE
    The thread executing in the Java virtual machine is in this state.
  • BLOCKED
    Threads that are blocked waiting for the monitor lock are in this state.
  • WAITING
    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 thread to perform an action for the specified waiting time is in this state.
  • TERMINATED
    Threads that have exited are in this state.
public class TestState {

    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();
                }
            }
        });

        Thread.State state = thread.getState();
        System.out.println(state);

        thread.start();

        state = thread.getState();
        System.out.println(state);
        while (state != Thread.State.TERMINATED) {
            Thread.sleep(100);
            state = thread.getState();
            System.out.println(state);
        }

    }

}

Thread priority priority

Java provides a thread scheduler to monitor all threads in the program that enter the ready state after startup. The thread scheduler decides which thread should be scheduled to execute first according to the priority

The priority is expressed in numbers, ranging from 1-10

Thread.MIN_PRIORITY=1;

Thread.MAX_PRIORITY=10;

Thread.NORM_PRIORITY=5;

Change or get priority

getPriority,setPriority(int i)

The priority setting is recommended to schedule money in start()

The low priority only means that the scheduling probability is low, not that it will not be called, or it depends on the CPU scheduling

Daemon

Threads are divided into user threads and daemon threads

The virtual machine must ensure that the user thread finishes execution

The virtual machine does not need to wait for the daemon thread to finish executing

Such as recording operation logs in the background, monitoring memory, waiting for garbage collection

setDaemon(true);

Guess you like

Origin blog.csdn.net/rr18758236029/article/details/108575618