当前位置:网站首页>Multithreading Basics: basic concepts of threads and creation of threads
Multithreading Basics: basic concepts of threads and creation of threads
2022-07-06 18:52:00 【Java Douluo】
One . Threads and processes
1. process
At first, the concept of thread and process may feel very abstract , Obscure , Look at the picture below :
Above, WIN10 System Task manager in , Operating system .exe The file can be understood as a process , It can be said that , Process is a basic running unit of operating system .
When it comes to process , It is necessary to talk about the procedure , A program consists of many instructions and data , Namely Command sequence .
These instructions need to be run , Data needs to be read and written , Instructions loaded into CPU, Give Way CPU Do the assigned task .
Data is loaded into memory , Instruction runtime , You need to use the Internet , Disk and other equipment . This process requires the process to load instructions , Manage memory , Handle IO Of .
So when a program runs , Loading code from disk to memory is equivalent to starting a process . For example, when Java Every time you compile .class file . It creates a JVM process .
We can think of a process as an instance of a program running , And most programs can run multiple process instances , Like Notepad , Google browser, etc , Some programs can only open one thread , Such as cool dog music .
2. Threads
Threads are equivalent to subtasks that run independently of each other in a process , These subtasks can have multiple , They share the resources owned by the process .
stay Java The middle process is the smallest unit of resource allocation , Thread as the smallest scheduling unit , There is a process first , There are threads after .
* Comparison and summary of the two *
1. Processes are independent of each other , Threads belong to a subset of processes and exist in threads .
2. Processes share system resources , Such as memory , The network port is used by its thread .
3. The communication between processes is more complex , This machine usually uses IPC Mechanism , Communication between different computers usually uses Socket perhaps Http Protocol to communicate .
4. Although threads are lighter than processes , But the cost of context switching of threads is very high .
Two . Parallelism and concurrency
2.1 Concurrent
Single task running environment ( Single core CPU) The thread execution mode is serial , Task scheduler in operating system , Will CPU The time slice is allocated to different programs to execute .
In the same period of time , The way threads execute in turn is called Concurrent 【concurrent】. In other words For a while , The need to deal with multiple things .
Let me give you an example , What is concurrency is easy to understand :
In a single core CPU Next , Now there are two threads to execute , But only one thread can get CPU Resources to run , Suppose that when threads 1 Start running to instruction 3 when , Must rely on threads 2 To carry out .
here CPU Will execute threads 2, And threads 1 Must wait for thread 2 Only after running ( Most of them are in the form of time slice rounds ) By constantly switching the threads that need to run , This is Concurrent 【Parallel】: The occurrence of two or more events in the same period of time .
This process runs fast , It's hard for us to feel , We feel like two threads are running at the same time , In a word, it is : Micro serial , Macro parallel .
2.2 parallel
It says , Concurrency is a period of time , The need to deal with multiple things . How to solve this demand , By parallel , So it can be said that parallelism is a way to solve concurrency .
The definition of parallelism is like this : It refers to two or more events occurring at the same time . Look at the picture below :
Now? , In multicore CPU Next , The above two threads do not need to wait for one party to finish executing , Instead, you can let two threads run at the same time , This is it. parallel .
3、 ... and . Synchronous and asynchronous
The concepts of synchronization and asynchrony are relatively simple , We understand it from the perspective of method :
Suppose there is A And B Two ways , call A Method must return the called result before execution B Method , This is Sync .
contrary , You can execute directly without waiting for the result to return B The way is asynchronous .
Multithreading is asynchronous , There are many applications of multithreaded asynchronous calls, to name a few :
1. The format conversion of large files can be run by a single thread , To prevent blocking .
2. tomcat Asynchronous in Servlet, Let user threads handle time-consuming tasks , prevent tomcat Blocking .
Four . Create thread
4.1 Inherit Thread
Before creating the thread class , First look at Thread class Construction :
public class Thread implements Runnable {}
Thread Class implementation Runable Interface ,Runable There is only one abstract method in the interface :
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
So the inheritance Thread class , You need to rewrite run() Method , Put the tasks processed by the thread into run() Method In the executor , Then by creating objects of this class , perform start() Method , Is the real sense of starting a thread .
Specific code :
/**
* MyThread It's a thread class
* @author Java Douluo (javaDouluo)
*
*/
public class MyThread extends Thread {
/**
* rewrite run Method
*/
@Override
public void run() {
System.out.println("MyRunThread===>" + Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
// Open thread
myThread.start();
// Current thread name
System.out.println("main===>"+ Thread.currentThread().getName());
}
}
Running results :
Be careful :
There are two threads on it , One is the main thread , There is also a thread created by ourselves , Don't think that the execution order of threads is the order in which the code is placed , This is related to you calling thread methods start() Is independent of the placement order .
4.2 Realization Runable Interface
When a thread class already has a parent class , Inherit Thread The method is not feasible , You can use the implementation Runable Interface To create a thread , It is an expansion of inheritance .
/**
* @author Java Douluo (javaDouluo)
* @date 2022 year 06 month 25 Japan 0:17
*/
public class MyRunable implements Runnable{
/**
* Realization Run Method
*/
@Override
public void run() {
System.out.println("MyRunThread===>" + Thread.currentThread().getName());
}
public static void main(String[] args) throws InterruptedException {
// Instantiate the current thread object
Runnable runnable = new MyRunable();
// Enter the current thread object into Thread
Thread thread = new Thread(runnable);
// Open thread
thread.start();
// Current thread name
System.out.println("main===>" + Thread.currentThread().getName());
}
}
The result of this method is the same as the above .
4.3 FutureTask coordination Thread
When the thread ends, we need to return a result that can be used FutureTask To pick up Take one Callable type To handle the case that there is a return result .
package com.jektong.thread.day01;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
/**
* @author Java Douluo (javaDouluo)
* @date 2022 year 06 month 27 Japan 23:10
*/
public class FutureTaskThread {
/**
* FutureTask Through cooperation Callable To achieve a return worthy effect
* @param args
*/
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> integerFutureTask = new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System.out.println("java");
TimeUnit.SECONDS.sleep(5);
return 0;
}
});
Thread thread = new Thread(integerFutureTask);
thread.start();
// Get the return value
integerFutureTask.get();
}
}
边栏推荐
猜你喜欢
随机推荐
AcWing 3537. Tree lookup complete binary tree
test about BinaryTree
爬虫玩得好,牢饭吃到饱?这3条底线千万不能碰!
根据PPG估算血压利用频谱谱-时间深度神经网络【翻】
If you have any problems, you can contact me. A rookie ~
视频化全链路智能上云?一文详解什么是阿里云视频云「智能媒体生产」
线代笔记....
朗坤智慧冲刺科创板:年营收4亿 拟募资7亿
Bonecp uses data sources
深度循环网络长期血压预测【翻译】
287. Find duplicates
AFNetworking框架_上传文件或图像server
【论文笔记】TransUNet: Transformers Make StrongEncoders for Medical Image Segmentation
同宇新材冲刺深交所:年营收9.47亿 张驰与苏世国为实控人
44所高校入选!分布式智能计算项目名单公示
Summary of performance knowledge points
Deep circulation network long-term blood pressure prediction [translation]
DOM Brief
[depth first search] Ji suanke: a joke of replacement
None of the strongest kings in the monitoring industry!