[Java multithreading] Java multithreading skills

Mu Xin 2021-11-25 18:30:57
java multithreading java multithreading skills


1. The concept of process and multithread and the advantages of thread

1.1 So what is thread ?

1.2 So why use multithreading ?

2. Using multithreading

2.1 Inherit Thread class

2.2 Realization Runnable Interface

2.3 Instance variables and thread safety

1. The concept of process and multithread and the advantages of thread

When it comes to multithreading, you have to mention “ process ” The concept , stay “ Baidu Encyclopedia ” The process is explained as follows :

process (Process) A program in a computer is about a running activity on a data set , Is the system resource allocation and scheduling of the basic unit , Is the foundation of the operating system architecture . In early process oriented computer architecture , A process is the basic execution entity of a program ; In modern thread oriented computer architecture , A process is a container for threads . A program is an instruction 、 Description of data and its organization , A process is an entity of a program .

A process is the basic unit of operation managed by the operating system .

1.1 So what is thread ?

Threads can be understood as subtasks running independently in a process . Thread refers to the process of program execution , An execution unit capable of executing program code . stay Java In language , Threads have 4 States : function 、 be ready 、 Suspend and end .

At the operating system level , The execution of the program is based on the process , Each process will have multiple threads executing concurrently without affecting each other .

1.2 So why use multithreading ?

(1) Using multithreading can reduce the response time of programs . In the case of a single thread , If an operation is time-consuming , Or wait a long time , At this time, the program will not respond to operations such as mouse and keyboard , After using multithreading , This time-consuming thread can be allocated to a separate thread to execute , So that the program has better interactivity .

(2) Compared with the process , Thread creation and switching are less expensive . Since starting a new process, this thread must be allocated a separate address space , Build many data structures to maintain thread code segments 、 Data segment and other information , Threads running in the same process share code segments 、 Data segment , The cost of starting or switching threads is much less than that of processes . At the same time, multithreading is very efficient in data sharing .

(3) many CPU Or multi-core computer itself has the ability to execute multithreading , If you use a single thread , Will not be able to reuse computer resources , Cause a huge waste of resources . therefore In a multiple CPU Using multithreading on a computer can improve CPU Utilization ratio .

(4) Using multithreading can simplify the structure of the program , Make the program easy to understand and maintain . A very complex process can be divided into multiple threads to execute .

【 notes 】: Multithreading is asynchronous , So don't put IDEA The order of the code is the order in which the thread executes , The thread is called at random .

2. Using multithreading

stay Java in , There are two ways to implement multithreaded programming ,

  • One is Inherit Thread class ,
  • The other is Realization Runnable Interface .

2.1 Inherit Thread class

public class Thread implements Runnable

From the above source code can be found ,Thread Class implements the Runnable Interface , There is a polymorphism between them .

Actually , Using inheritance Thread Class to create a new thread , The biggest limitation is that it does not support multiple inheritance , because Java The characteristic of language is single root inheritance , So in order to support multiple inheritance , It can be realized Runnable How to interface , Carry out and inherit at the same time . But with The nature of threads created in these two ways is the same , There is no essential difference .

example : Create a custom thread class MyThread.java, This class is inherited from Thread, And rewrite run Method .

public class MyThread extends Thread {
public void run() {

The running class code is as follows :

public class Run {
public static void main(String args) {
MyThread mythread = new MyThread();
System.out.println(" End of run !");

When using multithreading technology , The result of running code has nothing to do with the order of code execution or calling .

【 notes 】: If you call more than once start() Method , It will appear Exception in thread “main” java.lang.IlleagelThreadStateException.

Thread.java Class start() Method notice “ Thread Planner ” This thread is ready , Waiting to call the thread object run() Method . This process is actually to let the system arrange a time to call Thread Medium run() Method , That is to make the thread run , Start thread , have Asynchronous execution The effect of .

If you call code thread.run() It's not asynchronous execution 了 , It's synchronization , Then this thread object is not given to “ Thread Planner ” To process , But by the main Main program to call run() Method , That is to say, we must wait run() The code in the method can only be executed after execution .

【 notes 】: perform start() The order of methods does not represent the order in which threads start .

2.2 Realization Runnable Interface

Using inheritance Thread Class to develop multithreaded applications is limited in design , because Java It's a single inheritance , Multiple inheritance is not supported , So in order to change this limitation , You can use the implementation Runnable Interface to achieve multithreading technology .

Constructors Thread(Runnable target) Not only can it be introduced Runnable Object of the interface , You can also pass in a Thread Class object , It's quite possible to make a Thread Object run() Method is called by another thread .

example : Create an implementation Runnable The class of the interface MyRunnable, The code is as follows :

public class MyRunnable implements Runnable {
public void run() {
System.out.println(" Running !");

2.3 Instance variables and thread safety

The instance variable in the custom thread class can have... For other threads share and Do not share Points , This is a very important technical point in the interaction between multiple threads .

Here's a “ Non-thread safety ” Example :

public class MyThread extends Thread {
private int count = 5;
public void run() {
System.out.println(" from " + this.currentThread().getName() + " Calculation ,count = " + count);

Operation class Run.java The code is as follows :

public class Run {
public static void main(String[] args) {
MyThread mythread = new MyThread();
Thread a = new Thread(mythread, "A");
Thread b = new Thread(mythread, "B");
Thread c = new Thread(mythread, "C");
Thread d = new Thread(mythread, "D");
Thread e = new Thread(mythread, "E");

The above code , Think of multiple threads processing at the same time count The situation of , produce ” Non-thread safety “ problem .

In fact, this example is a typical sales scenario :5 A salesman , Each salesman can't get the same remaining quantity after selling a product , Only after each salesperson has sold out one item can other salespeople continue to reduce the number of new remaining items 1 operation . In this case, it is necessary to synchronize multiple threads , That is to say, it is necessary to queue up in order 1 operation . Change the code as follows :

public class MyThread extends Thread {
private int count = 5;
synchronized public void run() {
System.out.println(" from " + this.currentThread().getName() + " Calculation ,count = " + count);

By means of run Method before adding synchronized keyword , Make multiple threads execute run When the method is used , To deal with in a queue . When - One thread call run front , First judge run Is the method locked , If locked , Indicates that another thread is calling run Method , You have to wait for other threads to run After the method call is completed, you can execute run Method . In this way, the queued call run
Purpose of method , That is to say, we have reached the goal of pairing count Variable minus 1 The effect has been achieved. .synchronized You can lock any object or method , And the code that locks is called “ Mutual exclusion zone ” or “ A critical region ”.

When a thread wants to execute the code in the synchronization method , The thread first tries to get the lock , If you can get this lock , Then this thread can execute synchronize Code inside . If you can't get this lock , Then the thread will keep trying to get the lock , Until you can get it , And there are multiple threads competing for the lock at the same time .

本文为[Mu Xin]所创,转载请带上原文链接,感谢

  1. Java经典面试题详解,突围金九银十面试季(附详细答案,mysql集群架构部署方案
  2. java整理,java高级特性编程及实战第一章
  3. java教程——反射,mongodb下载教程
  4. Java岗大厂面试百日冲刺 - 日积月累,每日三题【Day12,zookeeper原理作用
  5. Java后端互联网500道中高级面试题(含答案),linux钩子技术
  6. java8 Stream API及常用方法,java初级程序员面试
  7. java-集合-Map(双列)——迪迦重制版,2021Java开发社招面试解答之性能优化
  8. Flink处理函数实战之二:ProcessFunction类,java线程面试题目
  9. flex 布局详解,【Java面试题
  10. Linux basic command learning
  11. Why did docker lose to kubernetes? Docker employee readme!
  12. MySQL安装
  13. Elastic Search Aggregate Learning five: Problem Analysis of Uncertainty of sequencing results, Alibaba Java Performance Tuning Practical
  14. Installing, configuring, starting and accessing rabbitmq under Linux
  15. Oracle SQL injection summary
  16. Installation MySQL
  17. L'exposition à la photo d'essai sur la route i7 du nouveau vaisseau amiral de BMW Pure Electric a également été comparée à celle de Xiaopeng p7.
  18. spring JTA 关于异常处理的时机问题
  19. Le problème du temps de traitement des exceptions dans la JTA printanière
  20. Flink Handling Function Real War II: processfunction class, Java thread interview subject
  21. Oracle SQL injection summary
  22. [Java data structure] you must master the classic example of linked list interview (with super detailed illustration and code)
  23. Do you really know MySQL order by
  24. Record a java reference passing problem
  25. spring JTA 關於异常處理的時機問題
  26. Java - Set - Map (double file) - dija Rewriting, 2021 Java Developer's Performance Optimization
  27. Android入门教程 | OkHttp + Retrofit 取消请求的方法
  28. Java 8 Stream API and common methods, Java Junior Program interview
  29. Github 疯传!史上最强!BAT 大佬,2021年最新Java大厂面试笔试题分享
  30. git(3)Git 分支,zookeeper下载教程
  31. Java Backend Internet 500 questions d'entrevue moyennes et avancées (y compris les réponses), technologie de crochet Linux
  32. Entretien d'entretien d'usine Java post sprint de 100 jours - accumulation de jours et de mois, trois questions par jour [jour 12, fonction de principe de Zookeeper
  33. Tutoriel Java - reflection, tutoriel de téléchargement mongodb
  34. How to analyze several common key and hot issues in redis from multiple dimensions
  35. GIT (3) GIT Branch, Zookeeper Download tutoriel
  36. Tutoriel de démarrage Android | okhttp + Retrofit comment annuler une demande
  37. Design pattern [3.3] - Interpretation of cglib dynamic agent source code
  38. Share the actual operation of private collection project nodejs backend + Vue + Mysql to build a management system
  39. Springboot has 44 application initiators
  40. GitHub上霸榜久居不下的《Java面试突击宝典》,java图形用户界面设计基础
  41. GitHub上访问下载破百万的神仙文档《Java面试神技》看完我呆了,java面试问项目中遇到的问题
  42. GitHub上标星75k 超牛的《Java面试突击版,java高级工程师技能
  43. GitHub上标星2,java项目开发实训教程
  44. Docker development environment Preview
  45. JavaScript高級深入淺出:掌握 this 指向
  46. JavaScript Advanced Insight and outside: Mastering this direction
  47. Vue de l'application pratique de Javascript, drop drag Event
  48. docker 安装部署 Jenkins 2.322
  49. kafka安装
  50. 近九万字图文详解RabbitMQ
  51. Engaged in Java for one and a half years, how to break through yourself
  52. 输出9*9乘法表----java
  53. 判断一个数是不是素数-------java
  54. java项目,记录页面修改值,内部打“官司”用
  55. Docker installation Deployment Jenkins 2.322
  56. Comment porter un pantalon en hiver? Les petits hommes, les jambes épaisses et la largeur de l'entrejambe peuvent être vus. 3 techniques pour éviter la foudre
  57. MySQL下载和安装教程
  58. In depth analysis of rocketmq source code - message storage module
  59. Spring transaction management
  60. mysql恢复ibd数据,为何频频报错?