Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Author’s other platforms:

| CSDN:blog.csdn.net/qq_4115394…

| the nuggets: juejin. Cn/user / 651387…

| zhihu: www.zhihu.com/people/1024…

| GitHub:github.com/JiangXia-10…

| public no. : 1024 notes

This article is about 7,469 words and takes 13 minutes to read

01 preface

The previous two articles explained some concepts and knowledge about threads, which are often asked about in development or job interviews. Before writing articles is also quite messy, what to think of what to write, there is no certain organization, so I prepare to record and summarize some knowledge points about threads in the way of a series of articles. I am also a learner myself, and I can strengthen my grasp and understanding of knowledge points by writing articles. So if there are some incorrect or incomplete places, please correct them.

Previous article Portal: Threads and common methods of threading; Six states of a thread; Volatile keyword resolution for Java concurrent programming.

A basic introduction to threads and thread creation and startup has been covered in previous articles, so this article is intended to summarize some of the commonly used APIS for threads.

There are many common apis for threads. Here are some common methods.

02 body

1. Sleep method

Sleep () is static, so the best method to call is thread.sleep (). Common formats are as follows:

Sleep (long millis) : The thread sleeps millis milliseconds

Sleep (long millis, int Nanos) : Thread sleep millis milliseconds + nanos nanoseconds

The thread’s sleep method should be written in the thread’s run() method to allow the corresponding thread to sleep for a specified amount of time.

The code is as follows:

package com.jiangxia.chap1; /** * thread sleep method * author: jiangxia * date:2021-04-14 */ public class Demo01 { public static void main(String[] args) { Thread t = new Thread1(); System.out.println(" start time "+ system.currentTimemillis ()); T.start (); System.out.println(" end time "+ system.currentTimemillis ()); }} class Thread1 extends Thread{@override public void run() { System.out.println(" thread start time: "+ system.currentTimemillis ()); Thread.sleep(10000); System.out.println(" thread end time "+ system.currentTimemillis ()); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

CurrentThread method

The currentThread() method returns information about which thread the segment is being called by. Thread.currendthread () gets the Thread object that uses the method. This gets the current object.

The code is as follows:

package com.jiangxia.chap1; /** * currentThread method * author: Jiangxia * date: 2021-04-14 */ public class Demo02 { public static void main(String[] args) { Thread t = new Demo8Thread(); t.start(); System.out.println("main method: "+ thread.currentThread ().getName()); }} Class Demo8Thread extends Thread{public Demo8Thread(){system.out.println (" constructor: "); System.out.println(" constructor: "+ thread.currentThread ().getName()); System.out.println(this.getName()); System.out.println(" Constructor end: '"); } @override public void run() {system.out.println ("run: "); System.out.println("run: "+ thread.currentThread ().getName()); System.out.println(this.getName()); System.out.println("run method ends: "); }}Copy the code

GetName (), getId()

The thread.getName () method returns the name of the current Thread. GetId is used to get the unique identity of the current thread.

package com.jiangxia.chap1; /** * getId * author: Jiangxia * date: 2021-04-14 */ public class Demo03 { public static void main(String[] args) { Thread thread = Thread.currentThread(); System.out.println(" threadname :"+thread.getName()); System.out.println(" thread ID:"+ thread.getid ()); }}Copy the code

4. IsAlive method

The function of isAlive() is to determine whether the current thread is active; The active state is true if the thread has been started but not terminated, if it is alive, and false otherwise.

The code is as follows:

package com.jiangxia.chap1; /** * isAlive method * author: Jiangxia * date: 2021-04-14 */ public class Demo9 { public static void main(String[] args) { Thread t = new Demo9Thread(); System.out.println(" Ready to start thread :"+ t.isalive ()); t.start(); System.out.println(" Thread started: "+ t.isalive ())); }} Class Demo9Thread extends Thread{public Demo9Thread(){system.out.println (" constructor start "); System.out.println(thread.currentThread ().isalive ())); // currentThread().isalive (); System.out.println(this.isAlive()); System.out.println(" constructor end "); } @override public void run() {system.out.println ("run "); System.out.println(thread.currentThread ().isalive ())); System.out.println("run: "+ this.isalive ()); System.out.println("run method ends "); }}Copy the code

5. GetState method

The getState() method returns the state of the thread. Threads have the following states:

state describe
NEW A thread that has not been started
RUNNABLE The thread that is executing in the Java virtual machine
BLOCKED Fill the thread that blocks waiting for an object lock
WAITING A thread that is waiting for another thread to perform a specific action
TIME_WAITING A thread that is waiting for another thread to execute until the specified wait time
TERMINATED A thread that has exited execution
package com.jiangxia.chap1; ** * Jiangxia * date: 2021-04-14 */ public class Demo1 { public static void main(String[] args) throws InterruptedException { Thread t = new Demo1Thread(); System.out.println(" thread status in main A: "+ t.gestate ()); Thread.sleep(2000); t.start(); Thread.sleep(2000); System.out.println(" thread status in main B: "+ t.gestate ()); }} Class Demo1Thread extends Thread{public Demo1Thread(){system.out.println (" class Demo1Thread extends Thread(){system.out.println (" "+Thread.currentThread().getState()); } @override public void run() {system.out.println (" thread.currentThread ().getState()); }}Copy the code

            

6. Yield method

The yield method gives up the current CPU resource so that another task can use it for execution. However, the abandonment time is uncertain. It is possible that the CPU time slice is acquired immediately after the abandonment.

The code is as follows:

package com.jiangxia.chap1; Public static void main(String[] args) {public static void main(String[] args) { Thread t1 = new Demo23Thread(); t1.start(); } } class Demo23Thread extends Thread{ @Override public void run() { int count =0; long starttime = System.currentTimeMillis(); for (int i = 0; i < 100000 ; i++) { yield(); count+=i; } long endtime = System.currentTimeMillis(); System.out.println(" calculate total time: "+(endtime-startTime)+" milliseconds "); }}Copy the code
Copy the code

The getPriority and setPriority methods get and set the priority of the thread

In an operating system, threads can be prioritized, and the higher priority thread gets more CPU resources, so the CPU will perform the tasks in the higher priority thread object first. Setting thread priority helps the Thread scheduler determine which thread is selected to execute first the next time.

The setPriority method is used to set the priority of a thread. The PRIORITY ranges from 1 to 10. If the priority is set to less than 1 or more than 10, the JDK throws IllegalArgumentException. The JDK defaults to three priority constants, MIN_PRIORITY=1(minimum), NORM_PRIORITY=5(median, default), and MAX_PRIORITY=10(maximum).

Get the priority of the thread using the getPriority method. Set the priority of a thread using the setPriority method.

package com.jiangxia.chap1; /** * getPriority, setPriority; Jiangxia * date:2021-04-14 */ public class Demo24 {public static void main(String[] args) System.out.println(" Thread.currentThread().getPriority() "); Thread.currentThread().setPriority(9); System.out.println(" Priority of main Thread after setPriority() : "+ thread.currentThread ().getPriority()); Thread t = new Thread24(); t.start(); }} Class Thread24 extends Thread{@override public void run() { System.out.println(" Thread priority: "+this.getPriority())); }}Copy the code

Note: Most high-priority threads always finish first, but this does not mean that all high-priority threads finish. When thread priorities vary widely, the order in which the code is called does not matter who finishes first.

Thread priority also has “randomness,” which means that the higher-priority line doesn’t always finish first.

Such as:

package com.jiangxia.chap1; import java.util.Random; /** * thread priority * author: Jiangxia * date:2021-04-14 */ public static void main(String[] args) {for (int i = 0; i <10 ; i++) { Thread t1 = new Thread25(); t1.setName("A"+i); // Set the highest level t1.setpriority (thread.max_priority) for t1 threads; t1.start(); Thread t2 = new Thread25(); t2.setName("B"+i); // set the lowest level t2.setpriority (thread.min_priority) for t2 threads; t2.start(); } } } class Thread25 extends Thread{ @Override public void run() { long start = System.currentTimeMillis(); long count = 0; for (int i = 0; i < 10; i++) { for (int j = 0; j <50000 ; j++) { Random r = new Random(); count = i*j + r.nextInt(); } } long end = System.currentTimeMillis(); System. Out. Println (" threads "+ enclosing getName () + completes the use of the" + (end - start), "ms"); }}Copy the code

SetDaemon sets the daemon thread

There are two types of threads in Java: User threads and daemons.

A daemon thread is a special thread, special in the sense that it will destroy itself when no user thread exists in the process. A typical example of a daemon thread is the garbage collector thread. When there are no user threads in the process, the garbage collector thread is no longer necessary and will be destroyed automatically.

Any daemon thread is the nanny of all non-daemon threads in the entire JVM. Daemons work as long as there are any non-daemons in the current JVM instance that have not terminated. The daemon thread terminates with the JVM only when the last non-daemon thread terminates. Daemons are designed to facilitate the running of other threads. The most typical use of daemons is the GARBAGE collector (GC).

There is little difference between the User Thread and the Daemon Thread, the only difference is that the virtual machine exits: if all the User threads exit and only the Daemon Thread remains, the virtual machine exits. Without the guardian, daemons have no work to do and no need to continue running.

The setDaemon method sets the specified thread to be a daemon thread. Such as:

package com.jiangxia.chap1; ** * jiangxia * date: 2021-04-15 */ public class Demo26 { public static void main(String[] args) throws InterruptedException { Thread thread =  new Thread26(); thread.setDaemon(true); Thread.start (); / / IllegalThreadStateException error message / / thread. SetDaemon (true); Thread.sleep(5000); System.out.println(" main thread ends "); }} Class Thread26 extends Thread{@override public void run() {while(true){try {system.out.println (); "+System.currentTimeMillis()); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }}}}Copy the code

Note:

1, thread. SetDaemon (true) must be in the thread. The start () set before, otherwise you will run out of a IllegalThreadStateException anomalies. A running regular thread cannot be set as a daemon thread.

2. New threads created in Daemon threads are also Daemon threads.

Daemon threads cannot be used to access inherent resources, such as read and write operations or computational logic. Because it can break at any time, even in the middle of an operation.

Java’s built-in multithreading frameworks, such as ExecutorService, convert daemons to user threads, so you can’t use Java’s thread pool if you want to use background threads.

03 summary

This is a summary of some common threads apis, and if you think they’re good or useful to you, share them with others.

I will continue to share some additional knowledge about multithreaded programming.

Related recommendations:

  • Six states of a thread

  • Threads and common methods for threads

  • Volatile keyword resolution for Java concurrent programming

  • What is the difference between a Cookie and a Session?

  • Do you know why the String class cannot be inherited?