当前位置:网站首页>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();
}
}
边栏推荐
- Self-supervised Heterogeneous Graph Neural Network with Co-contrastive Learning 论文阅读
- Shangsilicon Valley JUC high concurrency programming learning notes (3) multi thread lock
- 用于远程医疗的无创、无袖带血压测量【翻译】
- 华为0基金会——图片整理
- Certains marchés de l'emploi de Shanghai refusent d'embaucher des personnes qui se rétablissent positives à Xinguan
- 【论文笔记】TransUNet: Transformers Make StrongEncoders for Medical Image Segmentation
- Jushan database was among the first batch of financial information innovation solutions!
- C#/VB.NET 给PDF文档添加文本/图像水印
- 287. 寻找重复数
- Echart simple component packaging
猜你喜欢

2022-2024年CIFAR Azrieli全球学者名单公布,18位青年学者加入6个研究项目

手写一个的在线聊天系统(原理篇1)

When visual studio code starts, it prompts "the code installation seems to be corrupt. Please reinstall." Solution to displaying "unsupported" information in the title bar

Self supervised heterogeneous graph neural network with CO comparative learning

Hongke shares | plate by plate ar application in Beijing Winter Olympics

Mathematics in machine learning -- common probability distribution (XIII): Logistic Distribution

Online notes

使用cpolar建立一个商业网站(1)

Xu Xiang's wife Ying Ying responded to the "stock review": she wrote it!

裕太微冲刺科创板:拟募资13亿 华为与小米基金是股东
随机推荐
Helm deploy etcd cluster
287. 寻找重复数
Jushan database was among the first batch of financial information innovation solutions!
JDBC驱动器、C3P0、Druid和JDBCTemplate相关依赖jar包
Penetration test information collection - App information
人体骨骼点检测:自顶向下(部分理论)
二叉搜索树
AvL树的实现
多线程基础:线程基本概念与线程的创建
线代笔记....
Summary of performance knowledge points
SQL injection Foundation
Penetration test information collection - site architecture and construction
echart简单组件封装
Oracle advanced (IV) table connection explanation
epoll()无论涉及wait队列分析
POJ 2208 six lengths of tetrahedron are known, and the volume is calculated
Some understandings of tree LSTM and DGL code implementation
Afnetworking framework_ Upload file or image server
安装及管理程序