The use of the Thread class and the state flow of the thread

static method

currentThread() method

The currentThread() method can return information on which thread the code segment is being called by.

sleep() method

The purpose of the method sleep() is to put the current "executing thread" to sleep (suspend execution) for a specified number of milliseconds. This "executing thread" refers to the thread returned by this.currentThread().

There are two overloaded versions of the sleep method:

sleep(long millis)     //参数为毫秒
sleep(long millis,int nanoseconds)    //第一参数为毫秒,第二个参数为纳秒

sleep is equivalent to putting the thread to sleep, handing over the CPU, and letting the CPU perform other tasks.
But it is important to note that the sleep method does not release the lock, that is to say, if the current thread holds a lock on an object, even if the sleep method is called, other threads cannot access the object.

Note that if the sleep method is called, InterruptedException must be caught or thrown to the upper layer. When the thread sleep time is full, it may not be executed immediately, because the CPU may be executing other tasks at this time. So calling the sleep method is equivalent to putting the thread into a blocked state .

yield() method

Calling the yield method will cause the current thread to hand over the CPU permission, allowing the CPU to execute other threads. It is similar to the sleep method, which also does not release the lock. However, yield cannot control the specific time to hand over the CPU. In addition, the yield method can only allow threads with the same priority to have the opportunity to obtain the CPU execution time.

Note that calling the yield method does not make the thread enter the blocking state , but returns the thread to the ready state, it only needs to wait to reacquire the CPU execution time, which is different from the sleep method.

object method

start() method

start() is used to start a thread. When the start method is called, the system will start a new thread to execute user-defined subtasks. During this process, the corresponding thread will be allocated the required resources.

run() method

The run() method does not need to be called by the user. After starting a thread through the start method, when the thread obtains the CPU execution time, it enters the run method body to perform specific tasks. Note that inheriting the Thread class must override the run method and define the specific tasks to be performed in the run method.

getId()

The function of getId() is to obtain the unique identifier of the thread

isAlive() method

The function of the method isAlive() is to determine whether the current thread is active
code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MyThread  extends Thread{
     @Override
     public void run() {
         System.out.println( "run=" + this .isAlive());
     }
}
public class RunTest {
     public static void main(String[] args) throws InterruptedException {
         MyThread myThread= new MyThread();
         System.out.println( "begin ==" +myThread.isAlive());
         myThread.start();
         System.out.println( "end ==" +myThread.isAlive());
     }
}

The role of the method isAlive() is to test whether the thread is even alive. What is an active state? The active state is when the thread has been started and has not yet terminated. A thread is considered "alive" when it is in the running or ready to start state.
There is something to be aware of

1
System.out.println( "end ==" +myThread.isAlive());

Although the value printed in the above example is true, this value is undefined. The true value is printed because the myThread thread has not finished executing, so it outputs true. If the code is changed to the following, a sleep is added:

1
2
3
4
5
6
7
public static void main(String[] args) throws InterruptedException {
         MyThread myThread= new MyThread();
         System.out.println( "begin ==" +myThread.isAlive());
         myThread.start();
         Thread.sleep( 1000 );
         System.out.println( "end ==" +myThread.isAlive());
     }

Then the result of running the above code is false, because the mythread object has been executed within 1 second.

join() method

In many cases, the main thread creates and starts the thread. If the sub-thread performs a lot of time-consuming operations, the main thread will often end before the sub-thread ends. At this time, if the main thread wants to wait for the child thread to finish executing, for example, the child thread processes a piece of data, and the main thread wants to get the value in the data, it needs to use the join() method. The role of the method join() is to wait for the thread object to be destroyed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Thread4 extends Thread{
     public Thread4(String name) {
         super (name);
     }
     public void run() {
         for ( int i = 0 ; i < 5 ; i++) {
             System.out.println(getName() + "  " + i);
         }
     }
     public static void main(String[] args) throws InterruptedException {
         // 启动子进程
         new Thread4( "new thread" ).start();
         for ( int i = 0 ; i < 10 ; i++) {
             if (i == 5 ) {
                 Thread4 th = new Thread4( "joined thread" );
                 th.start();
                 th.join();
             }
             System.out.println(Thread.currentThread().getName() + "  " + i);
         }
     }
}

getName和setName

Used to get or set the thread name.

getPriority和setPriority

Used to get and set thread priority.

setDaemon and isDaemon

Used to set whether the thread becomes a daemon thread and determine whether the thread is a daemon thread.

The difference between a daemon thread and a user thread is that a daemon thread depends on the thread that created it, while a user thread does not. For a simple example: if a daemon thread is created in the main thread, when the main method finishes running, the daemon thread will also die. The user thread does not, the user thread will keep running until it finishes running. In the JVM, threads like garbage collectors are daemon threads.

Most of the methods in the Thread class have been mentioned above, so what changes will the thread state be caused by the method calls in the Thread class? The following picture is an improvement on the above picture:

suspend thread

The specific method of suspending the thread will be introduced in the next blog

interrupt() method

Thread state transition diagram


Guess you like

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