当前位置:网站首页>Multithreading and multithreaded programming
Multithreading and multithreaded programming
2022-07-28 00:57:00 【504 Gateway Time-out】
List of articles
Multithreading
What is thread
Threads are like processes “ Two places at once ”, The process can only do one thing at a time , If you need to do more than one thing at the same time , You need threads , A thread is a “ Execution flow ”, Multiple threads can “ meanwhile ” perform .
Reason for introducing thread
With the development , Single core CPU The development of is close to the extreme , In order to continue to improve computing power , It introduces multi-core CPU, The so-called concurrent programming is to make full use of multi-core resources to the greatest extent ; Although multiple processes can also realize concurrent programming , But if you frequently create processes and then destroy them , It will be less efficient , Multithreading can better solve this problem , Therefore, threads are also called “ Lightweight programming ”.
Why are threads lighter than processes ? In fact, it is due to the difference between process and thread creation process :
The process of creating a process is simple and can be understood as :
① establish PCB;
② Allocate system resources , It takes time ;
③ hold PCB Add to the two-way linked list of the kernel ;
The creation of threads :
① establish PCB;
② hold PCB Add to the two-way linked list of the kernel ;
The process of creating a thread is an improvement on the process , There is no more time-consuming operation of allocating resources , It will be lighter .
Some problems of multithreading
The introduction of multithreading is to improve efficiency , But if multicore resources are tight , It may backfire , Therefore, full multi-core resources are the main premise for multithreading to improve efficiency ;
The difficulty of multithreaded programming is thread safety , When multiple threads access the same variable , It may cause thread safety problems ;
When a thread in a process has a problem , For example, an exception is thrown , It must be handled in time , Otherwise, the whole process may collapse ;
Difference between process and thread (!)
- The process contains threads , A process can have multiple threads , At least one thread , The main thread ;
- Processes will not share the same memory ( Isolation, ), Different threads of a process share the same block of memory ;
- A process is the smallest unit of resources allocated by a system , Thread is the smallest unit of system scheduling ;
- When multiple processes execute at the same time , A process has failed , Generally, it will not affect other processes ( Independence of the process ), Multiple threads in a process execute simultaneously , A thread has failed , Will affect other threads ;
Create thread
A multithreaded program
class MyThread extends Thread{
@Override
public void run() {
System.out.println("hello thread");
}
}
public class Test1 {
public static void main(String[] args) {
Thread t=new MyThread(); // Upward transformation
t.start();
System.out.println("hello main");
}
}

A process has at least one thread , When running the above program , The operating system will call a java process , In this java A thread in the process called main( ) Method , This thread is the main thread ;
We generally think that , For the process , If in the process A Created a process B, We call it process A For the process B The parent process of , process B For the process A Can be inherited by child processes. ; But for threads , It is generally believed that threads are parallel , There is no parent thread or child thread .
The above running result shows that it is printed first hello main, But in fact, each thread is an independent execution flow , The execution between these execution flows is concurrent , The order of execution between two threads depends on the internal scheduling of the operating system , For us , It's random . therefore , Even if we run the program several times, the print results are consistent , We can't easily determine the execution result of the next program ;
A lot of times , Although we didn't create many threads manually , But when the program runs, it calls java process ,java There are usually many threads in the process , So how to check which threads are executing ?
In order to clearly see the executing thread , We use an endless loop to extend the execution time of the program :
class MyThread extends Thread{
@Override
public void run() {
while (true){
System.out.println("hello thread");
}
}
}
public class Test1 {
public static void main(String[] args) {
Thread t=new MyThread();
t.start();
while (true){
System.out.println("hello main");
}
}
}
Use jconsole.exe View the executing process :
Double-click on the run :

Find the thread :
there main And Thread-0 It's our own thread when the program is running , Other threads are java In process :
Using an endless loop , Program execution is too fast , You can use Thread.sleep( ) Methods to improve :
class MyThread extends Thread{
@Override
public void run() {
while (true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test1 {
public static void main(String[] args) {
Thread t=new MyThread();
t.start();
while (true){
System.out.println("hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

By running the results , Is it also more clearly observed 2 The scheduling of threads is random !
Create a multithreaded program
- Create a class inheritance Thread, Rewrite one of run( ) Method ;
The above multi-threaded program is actually created by this method , stay run( ) Internally, it indicates what task this multithread is to complete , Then, to create an instance is to assign the task to the newly created reference , Finally using start( ) Method is the real thread creation ;
- Create a class implementation Runnable, rewrite run( ) Method ;
class MyRunnable implements Runnable{
@Override
public void run() {
while (true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test2 {
public static void main(String[] args) {
Runnable runnable=new MyRunnable(); // Create examples
Thread t=new Thread(runnable); // Give the task to the thread
t.start();
while (true){
System.out.println("hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The way to create classes and inherit classes , In fact, the thread is bound with the task content ; This method of implementing the interface is to achieve the separation of threads and tasks ;
- Create a class inheritance Thread class , Non display inheritance , Use anonymous inner class ;
public class Test3 {
public static void main(String[] args) {
// Anonymous inner class
Thread t=new Thread(){
@Override
public void run() {
while(true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
}
}
- Use as anonymous inner classes Runnable;
public class Test4 {
public static void main(String[] args) {
Thread t=new Thread(new Runnable() {
@Override
public void run() {
while(true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
}
- Use lambda Expression to define the task ;
public class Test5 {
public static void main(String[] args) {
Thread t=new Thread(()->{
while (true){
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
lambda The essence of an expression is an anonymous function , It consists of parameters and return values , The syntax is :( Parameters )- > Return value
( Parameters )- > { Return value } ( Parameters can have multiple , There can be no );
Advantages of multithreaded programming
The biggest advantage of multithreaded programming is that it can improve the running speed , This is proved by the running time of single thread and multi thread :
The first is a single threaded program :
public class Test6 {
private static final long count=50_0000_0000l;
private static void serial(){
// Use System.currentTimeMillis() To record the current millisecond timestamp
long beg=System.currentTimeMillis();
int a=0;
for(long i=0;i<count;i++){
a++;
}
a=0;
for(long i=0;i<count;i++){
a++;
}
long end=System.currentTimeMillis();
System.out.println(" Time consumed by a single thread : " +(end-beg)+" ms ");
}
private static void concurrency(){
long beg=System.currentTimeMillis();
Thread t1=new Thread(()->{
int a=0;
for(long i=0;i<count;i++){
a++;
}
});
Thread t2=new Thread(()->{
int a=0;
for(long i=0;i<count;i++){
a++;
}
});
t1.start();
t2.start();
try {
t1.join();// call join Method in order to make t1 The main thread will execute after the thread execution of
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end =System.currentTimeMillis();
System.out.println(" Time consumed by concurrent execution :"+(end-beg)+ " ma");
}
public static void main(String[] args) {
serial();
concurrency();
}
}
Running results :
We can see from the running results that , Concurrent execution is faster ;
join() What the method needs to do is , When a new thread is added , The main thread will enter the waiting state , Until... Is called join() Method until the thread execution ends , This effectively avoids the impact of the main thread on the execution time ;
Multithreading scenarios
- CPU Dense scenes
Mentioned earlier , The introduction of multithreading is to maximize the use of CPU Multi core resources , therefore , stay CPU Multithreaded programming is also suitable for dense scenarios ; - IO Dense scenes
IO I.e. input and output , Because in IO In dense scenes , Almost no need to CPU It can quickly complete the operation of reading and writing data , It usually takes a lot of time to wait , At this time , Using multithreading can avoid CPU Too idle .
over!
边栏推荐
- When Jerry made a phone call, recording to SD card /u disk was not enough [article]
- 【OpenCV 例程 300篇】241. 尺度不变特征变换(SIFT)
- Multithreading & high concurrency (the latest in the whole network: interview questions + map + Notes) the interviewer is calm
- startUMl
- 投资80亿!南京华天封测一期项目即将投产!
- Leetcode 452. minimum number of arrows to burst balloons (medium)
- startUMl
- Recommend a Hongmeng instant messaging software "fruit chat", which is a bit awesome!!
- Branch and loop sentence exercises
- c# 反射之Type使用
猜你喜欢

startUMl

Read cmake in one article

网络安全漏洞分析与漏洞复现

Recommend a Hongmeng instant messaging software "fruit chat", which is a bit awesome!!

Code review tool

点分治解析

The server is poisoned - the dish is the original sin

Syntaxerror resolved: positive argument follows keyword argument

数据可视化-《白蛇2:青蛇劫起》(3)

Ink wheel salon | Li Wenjie, Peking University: a graph database system for knowledge atlas application gstore
随机推荐
Jerry, if you turn on Bluetooth again, one for two. When the mobile phone is connected to the prototype, it will appear and cannot be connected [chapter]
Buildforge materials
分支和循环语句题目练习
Array related knowledge
LSB steganography
迷惑的单片机矩阵按键
C type use of reflection
Function related knowledge
Jerry caused other messages to accumulate in the message pool [article]
Border width border fillet border color
Jmeter 如何解决乱码问题?
Valued at $36billion! SpaceX, which is about to launch its first manned launch, raised $346million
Leetcode - find the median of two positively ordered arrays
特权更改对现有连接的影响
[BuildRelease Management]Parabuild
Basic elementary function
Can TSMC Samsung build a production line without American equipment for Huawei?
mysql数据库的基本操作(三)-——基于字段
Ink wheel salon | Li Wenjie, Peking University: a graph database system for knowledge atlas application gstore
Branch and loop sentence exercises