当前位置:网站首页>[cornerstone of high concurrency] multithreading, daemon thread, thread safety, thread synchronization, mutual exclusion
[cornerstone of high concurrency] multithreading, daemon thread, thread safety, thread synchronization, mutual exclusion
2022-07-24 04:30:00 【Lazy sheep.java】
Study Directory
- Preface
- One 、 Processes and threads
- Two 、 Thread creation
- 3、 ... and 、 The essence of thread creation ()
- Four 、Thread Commonly used API、 Constructors
- 5、 ... and 、 User thread and daemon thread
- 6、 ... and 、 Thread safety
- 7、 ... and 、 Lock to achieve thread synchronization ()
- 8、 ... and 、 thread deadlock
- Nine 、 Thread interview eight part essay sorting ()
Preface
I've heard of three highs in Internet architecture a long time ago , High availability 、 High concurrency 、 High performance , Multithreading is the cornerstone of dealing with high concurrency problems , In the initial stage, you must have a deep impression of the thread system , Prepare for the future
One 、 Processes and threads
Threads (Thread): An execution path within a program .
call main The process of method is also an embodiment of thread execution . In the program , If there is only one execution path at the same time , This program is a single threaded program , At the same time , You can execute multiple threads. This program is a multithreaded program
process (Process): A program in a computer is about a running activity on a data set , Processes are created by threads , The container of the thread is also the entity of the program 
Multi process It means that the operating system can run multiple tasks at the same time ( Program )
Multithreading It refers to that there are multiple sequential flows executing in the same program , When main The simultaneous execution of multiple sub threads in a thread is the embodiment of multithreading
We usually use IDEA In the process of , After executing a program , Such a sentence will pop up at the end of the run box , Indicates the end of this process, marking the exit of the program 
Two 、 Thread creation
stay Java Pass through java.lang.Thread To represent threads , According to the idea of object-oriented ,Thread Class must provide us with a way to implement multithreading , So for programmers, the following implementation methods are derived
1. Inherit Thread class
① First define a subclass MyThread Inherit thread class Java.lang.Tread( That is to say Thread class ), And rewrite his interior run() Method
② establish MyThread Class object , Then we call the thread object. start() Method to start the thread
Just like this. :
public static void main(String[] args) {
MyThread m1 = new MyThread();
m1.start();// Start thread
}
class MyThread extends MyThread{
...}
excellent vacancy : stay Java Inheritance in object-oriented is a single inheritance pattern , Creating threads in the above way is simple in coding , But it will result in the inability to inherit other classes , Not conducive to expansion
2. Realization Runable Interface
① Define a thread task class (MyThread) Realization Runnable Interface , rewrite run() Method
② Create a task class (MyThread) object
③ Give the task object to Thread Handle , Calling the start() Method to start the thread
Just like this.
public static void main(String[] args) {
MyThread m1 = new MyThread();
new Thread(m1).start();// Implement the way that the interface starts the thread
}
class MyThread extends MyThread{
...}
advantage : The thread task class just implements the interface , You can continue to inherit classes and implement interfaces , More scalable
shortcoming : An additional layer of object packaging , If a thread has an execution result, it cannot return it directly
3. The inner class implements anonymity
The essence is to implement interfaces , It's just a short form
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" Threads started by anonymous inner classes ");
}
}).start();
4. Realization Callable、FutureTask Interface
① Get the task object
1. Define class implementation Callable Interface , rewrite call Method
2. use EutureTask hold Callable Object is encapsulated into a thread task object
② Give the thread task object to Thread Handle
③ call Thread Of start() Method to start the thread , Perform tasks
④ After thread execution 、 adopt Eutureask Of get Method to get the result of the task execution
This method is complicated , Few are used now , Just know
3、 ... and 、 The essence of thread creation ()
Through the above three ways , It's not difficult to find that they all need to pass start() Method to start the thread , Then perform the rewritten run() Method , We must not think that the thread effect is run() Methods: , He is an ordinary method that can't be more ordinary , We just rewrite it according to the rules , The purpose of the interface is to standardize , Rewrite here run() Method is a kind of normative embodiment , Even if you use ctrl+B Check its source code, and the result is that the usage cannot be found locally 
Actually , The essence of achieving threading effect is start0() Method instead of run(),start0() Method is the local method , yes JVM Machine is calling , The bottom is through C++ To achieve , Those who are interested can go debug Catch up with the source code private native void start0();
Four 、Thread Commonly used API、 Constructors
1.API: More commonly used are , Get thread name ——getName()、 Set the name ——setName()、 Get the current thread object currentThread()、 Start thread ——start()、 Thread termination ——interrupt()
public class Test {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
System.out.println("Hello world!");
System.out.println(" Current thread name :"+Thread.currentThread().getName());
}
}
Running results :
Hello world !
Current thread name :Thread-0
2. Thread to sleep ——sleep(), Let the thread sleep for a specified time ( In milliseconds )
Thread.sleep(1000);
3. Constructors
| Constructors | explain |
|---|---|
| public Thread( string name) | You can specify a name for the current thread |
| public Thread(Runnable target) | hold Runnable Object to thread object |
| public Thread(Runnable target ,String name ) | hold Runnable Object to thread object , And specify the thread name |
5、 ... and 、 User thread and daemon thread
Java Threads are mainly divided into User threads and The guardian thread
Understand these two concepts through seeing the name of a thing one thinks of its function The way is perfect , A user thread is a user , A daemon thread is a daemon that guards users all the time , When the user program finishes executing, the guardian exits silently
The most common :main After the thread exits , The sub threads inside are still running , When the daemon thread is turned on , The child thread will follow main Exit at the end of the thread
To create a daemon thread, you only need to call through this object setDaemon(true) It can be realized
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" The user thread is running ");
}
});
thread.setDaemon(true); // Turn on the daemons
thread.start();
Thread.sleep(1000);
System.out.println("main Thread end ~");
}
If all user threads have exited running , Only the daemons exist , The virtual machine exits . Because there is no one to protect , The daemon thread has no work to do , There is no need to continue running the program
Comparison before and after daemon thread startup :
Garbage collection mechanism is a typical daemon thread !
6、 ... and 、 Thread safety
When multiple threads operate the same shared resource at the same time, business security problems may occur , Called thread safety
Withdrawing money from life is a classic thread safety problem 
lazy sheep 、 Meiyang Yang goes to get the money of boiling sheep at the same time , Both threads are running at the same time, which meets the judgment conditions , As a result, the bank also lost 100000 , This is the production accident caused by thread safety
The reason for thread safety problems is the existence of multithreading concurrency 、 At the same time, there are actions to modify shared resources when accessing shared resources
So we need to synchronize threads !
7、 ... and 、 Lock to achieve thread synchronization ()
Synchronization mechanism : In the case of multithreaded programming , Some sensitive data is not allowed to be accessed by multiple threads at the same time , Use synchronous access technology , Ensure data at any one time , At most one thread accesses , To ensure the integrity of the data .
The mutex : Java In language , The concept of object mutex is introduced , To ensure the integrity of shared data operations . Each object corresponds to a can be called “ The mutex ” The tag , This sign is used to guarantee that at any moment , Only one thread can access the object .
keyword synchronized To contact the mutex of the object . When an object uses synchronized When decorating , Indicates that the object can only be accessed by one thread at any time

1. Synchronization code block
effect : Lock the core code with thread safety problems
principle : Only one thread can enter at a time , Automatically unlock after execution , Other threads come in to execute
synchronized( Synchronization lock object ){
Code for operating shared resources ( Core code )
}
2. Synchronization method
effect : Lock the core method of thread safety
principle : Only one thread can enter at a time , Automatically unlock after execution , Other threads will execute again
Modifier synchronized return type Method name ( Parameter list ){
Code for operating shared resources ( Core code )
}
After locking the object, thread synchronization can be realized, and multiple threads will not access the same shared resource at the same time ( The toll station on the highway can be abstracted into a lock )
Be careful : Synchronization also has corresponding limitations , It will reduce the execution efficiency of the program , Because fewer threads are started per unit time
8、 ... and 、 thread deadlock
Multiple threads occupy each other's lock resources , But refused to give in , Causes thread deadlock
Simulate a scene :
Code emulation :
class DeadLockDemo extends Thread {
static Object o1 = new Object();// resources 1
static Object o2 = new Object();// resources 2
boolean flag;
public DeadLockDemo(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if (flag) {
synchronized (o1) {
// Object mutex , The following is the synchronous generation
System.out.println(Thread.currentThread().getName() + " Get into 1");
synchronized (o2) {
// Get here li Object monitoring rights
System.out.println(Thread.currentThread().getName() + " Get into 2");
}
}
} else {
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + " Get into 3");
synchronized (o1) {
// Get here li Object monitoring rights
System.out.println(Thread.currentThread().getName() + " Get into 4");
}
}
}
}
- If flag by T, Threads A You'll get... First / hold o1 Object lock , Then try to get o2 Object lock
- If the thread A Don't get o2 Object lock , will Blocked
- If flag by F, Threads B You'll get... First / hold o2 Object lock , Then try to get o1 Object lock
- If the thread B Don't get o1 Object lock , will Blocked
Nine 、 Thread interview eight part essay sorting ()
interviewer : Please tell me the difference between process and thread
answer :
1. A process is the execution unit of a thread , There will be at least one thread in a process
2. Processes have independent memory space , Threads in the same process can share memory
3. Threads are the scheduling unit of memory processors, and processes are not
4. Both threads and processes can execute concurrently
5. Each independent process will have a corresponding program entry , But an independent thread cannot run independently , Must rely on a corresponding application
边栏推荐
- Will your NFT disappear? Dfinity provides the best solution for NFT storage
- conda 常用命令
- Live broadcast preview | practice sharing of opengauss' autonomous operation and maintenance platform dbmind
- PMIX ERROR: ERROR in file gds_ds12_lock_pthread.c
- 【ARC127F】±AB
- How to perform chowtest with Stata
- The second anniversary of open source, opengauss Developer Day 2022 full highlights review!
- Live classroom system 04 create service module
- 【望解答】数据无法正确同步了
- C语言:随机数的生成
猜你喜欢

Iqoo 10 series attacks originos original system to enhance mobile phone experience

Will your NFT disappear? Dfinity provides the best solution for NFT storage

(零八)Flask有手就行——数据库迁移Flask-Migrate

PostgreSQL source code learning (32) -- checkpoint ④ - core function createcheckpoint

postgresql源码学习(32)—— 检查点④-核心函数CreateCheckPoint

Design of two power dividers and directional couplers for basic experiment of microwave technology
![[untitled]](/img/c1/23797dd628641d524b55a125e95c52.png)
[untitled]

Basic learning notes of C language

Educational Codeforces Round 132 A - D

一次 svchost.exe 进程占用大量网络带宽的排查
随机推荐
【望解答】数据无法正确同步了
What is the general family of programmers working in first tier cities?
基于C语言设计的一个医院叫号系统
Analyze the real-time development method of Bank of London
C language classic exercises to write a program to find all the perfects within 1000.
Live broadcast preview | practice sharing of opengauss' autonomous operation and maintenance platform dbmind
阿里淘系面试题:Redis 如何实现库存扣减操作和防止被超卖?
Ambire wallet opens twitter spaces series
What are the 10 live demos showing? It's worth watching again whether you've seen it or not
[translation] announce krius -- accelerate your monitoring and adoption of kubernetes
LAN SDN technology hard core insider 10 cloud converged matchmaker evpn
Go language series - synergy GMP introduction - with ByteDance interpolation
Shell语法(一)
PostgreSQL source code learning (32) -- checkpoint ④ - core function createcheckpoint
【C语言】程序环境和预处理操作
How about opening an account for Guotai Junan Securities? Is it safe
[untitled]
Clickpaas, a low code service provider, has completed a strategic merger with BiP technology to jointly build an industrial digital base
buu web
Where is the difficulty in attracting investment in the park? Inventory of difficulties and difficulties in attracting investment in industrial parks