Detailed explanation of Java multithreading (5) ------ the declaration cycle of threads

Detailed explanation of Java multithreading (1) ------ Introduction of the concept: https://blog.csdn.net/weixin_39816740/article/details/80089790

Detailed explanation of Java multithreading (2)------How to create processes and threads: https://blog.csdn.net/weixin_39816740/article/details/80089834

Detailed explanation of Java multithreading (3) ------ synchronization of threads: https://blog.csdn.net/weixin_39816740/article/details/80089890

Java Multithreading Detailed Explanation (4) ------ Producers and Consumers: https://blog.csdn.net/weixin_39816740/article/details/80089972

 

This blog introduces the life cycle of threads.

  Thread is a dynamic execution process, it also has a process from creation to death.

In the Thread class, there is an enum inner class:

  

 

 

The above information is represented in pictures as follows:

  First picture:

  

 

  The second picture: regard waiting, timing waiting, and blocking as blocking a state

  

 

1. New state (new): use new to create a thread, just allocate memory space in the heap

           In the new state, the thread has not called the start() method to start, but there is only a thread object

          Thread t = new Thread();//This is the new state of the t thread

 

 

2. Runnable: The new state calls the start() method to enter the runnable state. And this is divided into two states, ready and running, which represent the ready state and the running state respectively.

    Ready state: The thread object calls the start() method, waiting for the JVM to schedule, (the thread is not running at this time)

    Running state: The thread object is scheduled by the JVM. If there are multiple CPUs, run multiple threads to run in parallel

  Note: The thread object can only call the start() method once, otherwise an error will be reported: illegaThreadStateExecptiong

 

3. Blocked state (blocked): The running thread gives up the CPU for some reason and temporarily stops running, and it will enter the blocked state. At this time, the JVM will not allocate CPU to the thread, until the thread re-enters the ready state, and has the opportunity to go to the running state.

  Note: The blocking state can only enter the ready state first, and cannot directly enter the running state

  The blocking state is divided into two situations:

    ①. When thread A is in a runnable state and tries to acquire a synchronization lock, it is acquired by thread B. At this time, the JVM puts the current thread A into the lock pool, and thread A enters the blocking state

    2. When the thread is in the running state, an IO request is issued, and it enters the blocking state at this time.

 

 

4. Waiting state (waiting): The waiting state can only be awakened by other threads. At this time, the parameterless wait() method is used.

  1. When the thread is running, the wait() method is called. At this time, the JVM puts the thread into the waiting pool

 

5. Timed waiting: the wait(long time) or sleep(long time) method with parameters is called

  1. When the thread is running, the wait method with parameters is called. At this time, the JVM puts the thread into the waiting pool

  ②, the current thread calls the sleep(long time) method

 

 

6. Terminated state (terminated): usually called the dead state, indicating that the thread is terminated

  ①, normal termination, after executing the run() method, normal termination

  ②, forced termination, such as calling stop() method or destroy() method

  ③, abnormal termination, exception occurs during execution

 

 

Several methods of threading are described in detail below:

  1. sleep (long millis) thread sleep: let the executing thread pause for a period of time and enter the timing waiting state.

    static void sleep(long millis): After calling this method, the current thread gives up CPU resources. Within the specified time, the thread where sleep is located will not get the chance to run, and the thread in this state will not release the synchronization lock (note and The difference between wait(), wait will give up CPU resources and also give up synchronization locks)

    This method is more used to simulate network latency, so that the error effect when multiple threads concurrently access the same resource is more obvious.

 

   2. join() joint thread: Indicates that this thread waits for another thread to complete (death) before executing. After the join method is called, the thread object is in a blocked state. Write in which thread, which thread blocks

    This is also called a joint thread, which means that the current thread and the thread where the current thread is located are combined into one thread

    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.ys.thread;
 
class Join extends Thread{
     @Override
     public void run() {
         for ( int i = 0 ; i < 10 ;i++){
             System.out.println( "播放音乐" +i);
         }
     }
}
 
public class ThreadTest {
     public static void main(String[] args) {
         //创建 join 线程对象
         Join joinThread = new Join();
         for ( int i = 0 ; i < 10 ; i++){
             System.out.println( "玩游戏" +i);
             if (i== 3 ){
                 joinThread.start();
             }
             if (i== 5 ){
                 try {
                     joinThread.join(); //强制运行 join 线程,知道 join 运行完毕了,main 才有机会运行
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         }
     }
 
}

  result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
玩游戏 0
玩游戏 1
玩游戏 2
玩游戏 3
玩游戏 4
玩游戏 5
播放音乐 0
播放音乐 1
播放音乐 2
播放音乐 3
播放音乐 4
播放音乐 5
播放音乐 6
播放音乐 7
播放音乐 8
播放音乐 9
玩游戏 6
玩游戏 7
玩游戏 8
玩游戏 9

  

 

 

Background thread (daemon thread): A thread running in the background whose purpose is to provide services to other threads, also known as a "daemon thread".

1. The garbage collection thread of the JVM is the daemon thread.

②, the main method is the foreground thread, not the background thread

  

1
2
3
4
5
6
7
public static void main(String[] args) {
         String mainThreadName = Thread.currentThread().getName();
         System.out.println(mainThreadName);  //main
         
         System.out.println(Thread.currentThread().isDaemon()); //false
         
     }

  

Features:

1. If all foreground threads die, the background threads automatically die;

②, the foreground thread does not end, the background thread will not end;

3. The thread created by the foreground thread is the foreground thread, and the thread created by the background thread is the background thread.

  Thread.setDaemon(Boolean on) must be called before the start() method. Otherwise, an error will be reported.

 

 

 

 

Thread priority:

  Each thread has a priority, which helps the system determine the order in which threads should be dispatched.

  The priority of a Java thread is an integer, the value range is: 1 (Thread.MIN_PRIORITY) - 10 (Thread.MAX_PRIORITY)

  By default, each thread is assigned a priority NORM_PRIORITY (5).

  具有较高优先级的线程对程序更重要,并且应该在低优先级的线程之前分配处理器资源。但是,线程优先级不能保证线程执行的顺序,而且非常依赖于平台。

 

 

 

 

线程礼让:

yield()方法:表示当前线程对象提示调度器自己愿意让出 CPU 资源,但是调度器可以自由的忽略该提示。

       调用该方法后,线程对象进入就绪状态,所以完全有可能:某个线程调用了 yield() 方法,但是线程调度器又把它调度出来重新执行。

从 Java7 提供的文档上可以清楚的看出,开发中会很少使用该方法,该方法主要运用于调试或测试,它可能有助于多线程竞争条件下的错误重现现象。

 

sleep() 和 yield() 方法的区别:

  ①、都能使当前处于运行状态的线程放弃 CPU资源,把运行的机会给其他线程

  ②、sleep 方法会给其他线程运行的机会,但是不考虑其他线程优先级的问题;yield 方法会优先给更高优先级的线程运行机会

  ③、调用 sleep 方法后,线程进入计时等待状态,调用 yield 方法后,线程进入就绪状态。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325567808&siteId=291194637
Recommended