Java Advanced Series Concurrent Programming Chapter 5 thread API

The nickname is not recognized 2021-01-23 20:04:26
java advanced series concurrent programming


In the last article, I introduced Thread Construction method of class , But it's not enough just to have a construction method , We have to learn more about this kind of common API Talent , Only in this way can we have a deeper understanding of this category , It also gives us more choices .

Thread Class provides the API There are dozens of , Because of space , This article only chooses several representative ones to explain . remainder API Friends interested can view through the source code , You can also leave me a message , Let's discuss and learn together .

The goal is

  1. currentThread
  2. setPriority
  3. yield
  4. sleep
  5. interrupt
  6. interrupted
  7. join

Content

1. currentThread

This method is used to return a reference to the current thread of execution , We can get the current thread object through it in the code block , It seems so simple , But it's very widely used , This method will be widely used in subsequent content .

Method :

public static native Thread currentThread();

Code :

/**
* We can see in this example Thread.currentThread() What we get here are the reference objects of the respective execution threads .
*/
public class CurrentThreadDemo {
public static void main(String[] args) {
// The result is :true
Thread t = new Thread(() -> {
System.out.println("t".equals(Thread.currentThread().getName()));
}, "t");
t.start();
// The result is :true
System.out.println("main".equals(Thread.currentThread().getName()));
}
}

2. setPriority

A process has its priority , Threads also have priorities , In theory, threads with higher priority will be given priority CPU To schedule , But it's not always what you want .

If CPU Busy , Setting priorities may get more CPU Time slice , But in CPU In my spare time , Setting priorities has little effect . therefore , Let's not try to use priority in programming to bind certain businesses or make businesses depend on priority , The result may be inconsistent with what you expect .

Method :

public final void setPriority(int newPriority); // Set thread priority
public final int getPriority(); // Get thread priority 

Case study :

/**
* t1 The priority of a thread is higher than t2 The thread is low , Normally, it should be more than t2 Less threads
* But the number of random tests I have here is :
* t1: 59573
* t2: 34321
* Different CPU The resource situation will have different running results , You can test it a few times
*/
public class PriorityDemo {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
System.out.println("t1");
}
}, "t1");
Thread t2 = new Thread(() -> {
while (true) {
System.out.println("t2");
}
}, "t2");
// The minimum value is :1, The median value is :5, The maximum value is :10
t1.setPriority(9);
t2.setPriority(10);
t1.start();
t2.start();
}
}

3. yield

yield Method is a heuristic method , It prompts the scheduler that the current thread is willing to give up the current use of the processor . The scheduler is free to ignore this prompt . Its use should be combined with detailed performance analysis and benchmarking , To ensure that it actually has the desired effect .

This method is rarely used . For debugging or testing purposes , It can be very useful , Because it may help to recreate the errors caused by competitive conditions .

Method :

public static native void yield();

Case study :

/**
* If you let go of the comments section, you can see that the output of the console is sometimes 0 in front , Sometimes it's 1 in front
* And after this part is annotated , You'll find that one is all 0 in front
*/
public class YieldDemo {
public static void main(String[] args) {
IntStream.range(0, 2).mapToObj(YieldDemo::test).forEach(Thread::start);
}
private static Thread test(int index){
return new Thread(() -> {
// if (index == 0){
// Thread.yield();
// }
System.out.println(index);
});
}
}

4. sleep

sleep It's a static method , According to the precision and accuracy of the system timer and scheduling program , Put the currently executing thread into sleep state ( To suspend execution ) To the specified number of milliseconds . This thread will not lose ownership of any monitors ( for example monitor lock , About monitor Lock will be explained in detail in the following article ).

Method :

public static native void sleep(long millis); // The number of milliseconds to sleep
public static void sleep(long millis, int nanos); // Milliseconds and nanoseconds of sleep 

Case study :

/**
* In this case , We sleep in the custom thread and the main thread respectively , The hibernation of each thread does not affect each other
* Thread.sleep() Will only cause the current thread to sleep for a specified time
*/
public class SleepDemo {
public static void main(String[] args) {
new Thread(() -> {
long startTime = System.currentTimeMillis();
sleep(2000);
System.out.printf("%s Thread time :%d%s", Thread.currentThread().getName(), System.currentTimeMillis() - startTime, "ms");
System.out.println("");
}, "t").start();
long startTime = System.currentTimeMillis();
sleep(3000);
System.out.printf("%s Thread time :%d%s", Thread.currentThread().getName(), System.currentTimeMillis() - startTime, "ms");
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

yield and sleep The difference between :

  • yield Just for CPU A hint from the scheduler , If it works , Will cause thread context switching ;
  • sleep Causes the current thread to pause for a specified time , No, CPU Time slice consumption ;
  • yield Will cause the thread to run from RUNNING Status entry RUNNABLE state ;
  • sleep Makes the thread short block, Then release... In a given time CPU resources ;
  • yield There is no guarantee that it will take effect , and sleep Almost 100% sleep at a given time ( The final sleep time should be based on the accuracy of the timer and scheduler of the system )
  • yield Unable to capture interrupt signal , and sleep If it is interrupted by another thread, the interrupt signal can be captured

5. interrupt

Threads interrupt Is a very important one API, It's also a common method , If you're calling :

  1. Object Class wait(),wait(long) or wait(long,int) Method or join(),join(long),join(long,int) The thread is blocked when the method of , This kind of sleep(long) or sleep(long,int) Method , The interrupt status will be cleared , And will receive InterruptedException.
  2. InterruptibleChannel Of I/O operation , The channel will be closed , The interrupt state of the thread will be set , And the thread will receive java.nio.channels.ClosedByInterruptException.
  3. Selector Of wakeup Method , The interrupt state of the thread is set , And it will immediately return from the selection operation ( May have a non-zero value ), It's like calling the selector's wake-up method .

Related to it API There are several more. .

Method :

public void interrupt(); // Interrupt blocking
public static boolean interrupted(); // Determine whether the current thread is interrupted , This method will directly erase the thread's identity
public boolean isInterrupted(); // Determine whether the current thread is interrupted , Judgment alone does not affect the identification
// interrupted and isInterrupted Methods call local methods isInterrupted() To achieve , The parameters in this method ClearInterrupted Mainly used to control whether to erase threads interrupt The logo of , After the logo is erased , All subsequent judgments will be false
private native boolean isInterrupted(boolean ClearInterrupted);

Case study :

/**
* Create a new thread t, Sleep 1 minute
* Main thread sleep 2 Seconds later , For threads t Interrupt , Console output :interrupt, Program end
*/
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
System.out.println("interrupt");
}
}, "t");
t.start();
Thread.sleep(2000);
t.interrupt();
}
}

Inside the thread, there is a thread named interrupt flag The logo of , If a thread is interrupt, So it's flag Will be set , We can also see the corresponding description in the source code .

public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}

But if the current thread is executing an interruptible method and is blocked , call interrupt Method to interrupt it , On the contrary, it will lead to flag Be clear , This point will be described in detail in later articles .

7. join

Thread Of join Method is also a very important method , Many powerful functions can be realized by using its features , stay Thread Class gives us three different Method , As follows .

Method :

public final void join(); // Wait permanently for the end of the thread's life cycle
public final synchronized void join(long millis); // Set the maximum wait milliseconds value , by 0 And wait forever
public final synchronized void join(long millis, int nanos); // Set the maximum waiting milliseconds and nanoseconds , by 0 And wait forever 

Case study :

/**
* Create two threads 1 and 2 And start them separately , Output on the console .
* meanwhile main Thread calls the methods of these two threads , And you'll find that threads 1 and 2 The output alternates until both threads are running
* here main The thread begins to loop output , If you will join Method commented out , Three threads will output at the same time
*/
public class JoinDemo {
public static void main(String[] args) throws InterruptedException {
List<Thread> list = IntStream.range(1, 3).mapToObj(JoinDemo::getThread).collect(Collectors.toList());
list.forEach(Thread::start);
for (Thread thread : list) {
thread.join();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static Thread getThread(int name){
return new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, String.valueOf(name));
}
}

summary

In this article , We learned Thread Some of the more common API,Thread Of API It is the foundation of mastering high concurrency programming , It is very necessary to master !

This is the end of today's article , If you have any suggestions or opinions, please contact me for improvement , Your support is my biggest motivation !!!
This article is a platform of operation tools such as blog group sending one article and multiple sending OpenWrite Release
版权声明
本文为[The nickname is not recognized]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210123200322710Z.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云