current position:Home>Roommate hit the king and learned Java multithreading..
Roommate hit the king and learned Java multithreading..
2022-01-27 04:39:59 【Silent King II】
about Java For beginners , Many of the concepts of multithreading sound difficult to understand . For example :
- process , Is the encapsulation of the runtime program , It is the basic unit of resource scheduling and allocation in the system , The concurrency of the operating system is realized .
- Threads , Is a subtask of a process , yes CPU Basic unit of dispatch and dispatch , It realizes the concurrency within the process .
Very abstract , Isn't it ? Make a comparison , You're beating the king ( Actually, I can't play doge):
- The process can be compared to the game you played
- Threads can be compared to heroes of your choice or crystal monsters in the game .
Take this metaphor to understand the relationship between process and thread , A process that can have multiple threads is called multithreading . Does it feel very easy to understand ?
1、 The thread is under the process
( A separate hero 、 Wild monster 、 Small soldiers certainly can't run )
2、 Processes don't interact with each other , The end of the main thread will lead to the end of the whole process
( There will be no connection and influence between the two games . Your crystal was pushed away , Your game is over )
3、 Different process data is difficult to share
( It's hard to connect between the two games , Related situations, such as the enemy of the upper hand, which is matched to )
4、 Data can be easily shared between different threads in the same process
( The game you played , You can see the status of each player —— Life and death , You can also see the output of each player and so on )
5、 The memory address used by the process can limit the usage
( Open room mode , Determines how many people you can set to enter , When the room is full , No one else can get in , Unless someone leaves the room , Other talents can enter )
After understanding the above concepts , Let's look at two ways to create multithreads :
①: Create a class inheritance Thread class , And rewrite run Method .
public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(getName() + ": I hit " + i + " A little soldier "); } } }
Let's write a test method to verify :
// establish MyThread object MyThread t1=new MyThread(); MyThread t2=new MyThread(); MyThread t3=new MyThread(); // Set the name of the thread t1.setName(" ruban "); t2.setName(" Liu bei "); t3.setName(" Arthur "); // Start thread t1.start(); t2.start(); t3.start();
Let's take a look at the results after implementation :
②: Create a class implementation Runnable Interface , And rewrite run Method .
public class MyRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { try {//sleep An exception will occur to show the processing Thread.sleep(20);// Pause 20 millisecond } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " I hit :" + i + " A little soldier "); } } }
Let's write a test method to verify :
// establish MyRunnable class MyRunnable mr = new MyRunnable(); // establish Thread Parametric construction of class , And set the thread name Thread t1 = new Thread(mr, " Zhang Fei "); Thread t2 = new Thread(mr, " The sable cicada "); Thread t3 = new Thread(mr, " Lyu3 bu4 "); // Start thread t1.start(); t2.start(); t3.start();
Let's take a look at the results after implementation :
1、 Why rewrite run Method ?
because run Method is used to encapsulate the code executed by the thread .
2、run()
Methods and start()
What's the difference ?
run()
: Encapsulating code executed by threads , A direct call is equivalent to calling a normal method .start()
: Start thread , Then from JVM Calling therun()
Method .
3、 By inheritance Thread Method and implementation of Runnable Interface way to create multithreading , Which good ?
Realization Runable Good interface , There are two reasons :
- ①、 Avoided Java Limitations of single inheritance
- ②、 It is suitable for multiple same program codes to deal with the same resource , Thread 、 Effective separation of code and data , More in line with the object-oriented design idea .
For thread control , You will also encounter 3 There are two common ways , Let's introduce them one by one .
1)sleep()
: Pauses the currently executing thread for the specified number of milliseconds , That is, go into sleep .
It should be noted that ,sleep The exception should be handled when .
try {//sleep An exception will occur to show the processing Thread.sleep(20);// Pause 20 millisecond } catch (InterruptedException e) { e.printStackTrace(); }
2)join()
: Wait for this thread to finish executing before it's turn for subsequent threads to get cpu The enforcement of , Using this also throws an exception .
// establish MyRunnable class MyRunnable mr = new MyRunnable(); // establish Thread Parametric construction of class , And set the thread name Thread t1 = new Thread(mr, " Zhang Fei "); Thread t2 = new Thread(mr, " The sable cicada "); Thread t3 = new Thread(mr, " Lyu3 bu4 "); // Start thread t1.start(); try { t1.join(); // wait for t1 It's only after execution that it's your turn t2,t3 rob } catch (InterruptedException e) { e.printStackTrace(); } t2.start(); t3.start();
Let's take a look at the results after implementation :
3)setDaemon()
: Mark this thread as a guardian thread , To be precise , Is to serve other threads , image Java Garbage collection thread in , Is a typical daemon thread .
// establish MyRunnable class MyRunnable mr = new MyRunnable(); // establish Thread Parametric construction of class , And set the thread name Thread t1 = new Thread(mr, " Zhang Fei "); Thread t2 = new Thread(mr, " The sable cicada "); Thread t3 = new Thread(mr, " Lyu3 bu4 "); t1.setDaemon(true); t2.setDaemon(true); // Start thread t1.start(); t2.start(); t3.start();
If all other threads have finished executing ,main Method ( The main thread ) It's done ,JVM You're going to quit , That is, stop running . If JVM It's all down , The daemon thread naturally stops .
Finally, let's take a look at the thread life cycle , A picture is worth a thousand words .
The idea and most of the content of this article come from iron powder Hold for a long time , It's very interesting , ha-ha . The second brother made some adjustments , Hope to give beginners Java Multithreaded little partner, a little help and inspiration .
by the way , This article has been included in 《Java The road to advancement of programmers 》 Columnar 「 Concurrent programming 」 piece , The column is in GitHub The harvest has been 832 Mei xingbiao :
https://github.com/itwanger/toBeBetterJavaer
I hope more and more Java Enthusiasts can benefit from this open source project , and More and more people are star, It will also inspire me to create better content ~
copyright notice
author[Silent King II],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270439569627.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command