当前位置:网站首页>Summary of thread implementation
Summary of thread implementation
2022-07-06 14:37:00 【Floating~】
Tips : Before reading this article , Please first understand the basic concepts of threads and processes in the operating system .
The basic concept of thread will be mentioned in this article , Please refer to my two notes for operating system and process https://note.youdao.com/s/ag3ipekEhttps://note.youdao.com/s/ag3ipekE
https://note.youdao.com/s/BFTOv61yhttps://note.youdao.com/s/BFTOv61y
Catalog
One 、 The basics of multithreading
1.2 When multithreading is needed
1.3 The advantages and disadvantages of multithreading
1.4 Multithreaded species state
2.2 Realization Runnable Interface
2.3 Realization Callable Interface
Preface :
At the system level , In order to reduce the time-consuming operation , Improve the efficiency of program parallel operation and CPU Utilization ratio , We introduced the technical concept of multithreading .、
This article will start with the basic concept of thread , Introduce in detail the four ways to create multithreading .
One 、 The basics of multithreading
1.1 What is thread
A thread is an executable unit inside a process , It is a sequence control process that can complete an independent task , If you run multiple threads in a process at the same time , To do different things , It's called multithreading .
1.2 When multithreading is needed
(1) When the program needs to perform two or more tasks at the same time .
(2) When the program needs to perform some tasks that need to wait , For example, user registration , File read and write .
(3) When the background execution program is required .
1.3 The advantages and disadvantages of multithreading
advantage :
- It can appropriately improve the execution efficiency of the program
- Can properly improve the utilization rate of resources (cpu、 Memory utilization )
shortcoming :
- Starting a thread requires a certain amount of memory space ,( By default , The main thread 1M, Sub thread 512KB), If you start a lot of threads , It takes up a lot of memory space , Reduce the performance of the program .
- More threads ,cpu The higher the overhead on the scheduling thread .
- Programming is more complicated : For example, the communication between threads 、 Multithreaded data sharing
1.4 Multithreaded species state
- NEW: New state . When a thread is created , Before starting , In that state .
- RUNNABLE: Operational state . When a thread is executing a task , In that state .
- WAITING: Infinite waiting state . A thread gets Lock Lock object , Failure , In that state .
- TIMED_WAITING: Time waiting state . When a thread is executing sleep Method time , In that state .
- BLOCKED: Blocked state . A thread gets synchronized( Code block 、 Method ) Lock object , Failure , In that state .
- TERMINATED: Die state . When the thread finishes executing the task , In that state .
among NEW State and TERMINATED The status will only appear once .
Two 、 Thread implementation
Creating a sub thread is : establish Thread Object of type , And start execution .
2.1 Inherit Thread class
Thread class :
Package :java.lang;
Construction method :
public Thread();
public Thread(Runnable target);
public Thread(Runnable target,String name);
Static methods :
static Thread currentThread();// Get the current thread , Which thread executes the method , Just get which thread
Member method :
void start();// It can only be called once , Cannot call more than once
void run();// After the thread starts , Will execute run The code in the method
String getName();// Get the name of the thread
void setName(String name);// Set the name of the thread
Inherit Thread The steps to create a thread of class are as follows :
- Create an inheritance from Thread Subclasses of classes .
- rewrite Thread Class run Method –> Declare the operation performed by this thread in run() in .
- Create subclass objects .
- Called by subclass object start() Method .
establish Thread Class object , rewrite run() The code of the method is as follows :
public class Test01Thread {
public static void main(String[] args) {
// Create... As an anonymous inner class Thread Object of type , Create thread
Thread t = new Thread() {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name);
}
};
t.start();// Start thread
};
}
2.2 Realization Runnable Interface
Runnable Interface :
Runnable Than Thread The advantages of class :
1. You can avoid java The limitations of single inheritance in (java It is single inheritance and multi-level inheritance , And implementation is multi implementation )
2. Task and thread separation , Realize understanding coupling
3. Thread pool can only be passed in Runnable perhaps Callable Object of type , You cannot use inheritance
Realization Runnable The steps to create a thread for the interface are as follows :
- Create an implementation Runnable The class of the interface
- Realization Runnable Methods in interfaces .
- Create objects that implement classes .
- Pass this object as an argument to Thread In the constructor of class , establish Thread Class object .
- adopt Thread Class object call start() Method .
Realization Runnable The code of the interface creation thread is as follows :
public class Test02Runnable {
public static void main(String[] args) {
// Use anonymous inner classes to create Runnable Object of type
Runnable r = new Runnable() {
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name);
}
};
// Create thread
Thread t = new Thread(r," Threads 1");
t.start();
}
}
2.3 Realization Callable Interface
callable Interface :
Realization Callable The interface steps are as follows :
- Create subclass implementation callable Implementation class of .
- Realization call Method , Declare the operation that this thread needs to perform in call In the method .
- establish Callable Interface object
- Put this Callable The object of the implementation class is passed as a parameter to FutureTask The constructor , establish FutureTask object .
- take FutureTask The order of the class is passed to Thread In the constructor of class , establish Thread Class object , Start the thread through this object
- Can get Callable Implementation class call Return value of method .( Optional , If you need a return value get, No need, no get)
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class Test03Callable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Create by anonymous inner class Callable Object of type
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName());
return " There are return values ";
}
};
// establish FutureTask The object accepts callable Return value result
FutureTask<String> ft=new FutureTask(callable);
// Create thread
Thread t=new Thread(ft);
// Start thread
t.start();
// Get the return result of the thread
String str = ft.get();
System.out.println(str);// test Callable The return value of
}
}
2.4 Thread pool
Thread pool creates threads :
advantage :
1. Reduce resource consumption ( Reduce the frequent creation and destruction of threads ).
Threads in the thread pool can be created in advance , And you can only finish the task without destroying
2. Improve response time . Threads in the thread pool can create threads in advance .
3. Improve the manageability of threads .( There are many tasks , And each task takes a long time )
Creating a thread takes about 1M Space .
grammar :
Executors class
static ExecutorService newFixedThreadPool(int c);// The parameter is the number of threads
ExecutorService Interface :
void execute(Runnable r);
Future<?> submit(Runnable r);// If the thread returns a value after executing the task , You can process the returned results
<T> Future<T> submit(Callable<T> c);
void shutdown();// Close thread pool
Future<T> Interface
T get();// You must wait for the execution of the subthread task to end , To get the returned result .
Realization Runnable Interface , Create threads with thread pool .
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test04Executors {
public static void main(String[] args) {
// Create a fixed thread pool object ,2 Create two threads for .
ExecutorService threadPool = Executors.newFixedThreadPool(2);
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
// Perform tasks
threadPool.execute(r);
// close
threadPool.shutdown();
}
}
Realization Callable Interface , Create threads with thread pool , And get the return value .
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test05ExecutorsCall {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Create thread pool object
ExecutorService threadPool = Executors.newFixedThreadPool(1);
// Create by anonymous inner class Callable Object of type
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName());
Thread.sleep(10000);
return " There is a return value ";
}
};
// Perform tasks
Future<String> future = threadPool.submit(callable);
// Get the return result of the thread .
String str = future.get();
System.out.println(str);// test Callable The return value of
// close
threadPool.shutdown();
}
}
Last , Thank you for your continued support !!!
Learn from time to time , To make progress .
边栏推荐
- Pointers: maximum, minimum, and average
- Bing Dwen Dwen official NFT blind box will be sold for about 626 yuan each; JD home programmer was sentenced for deleting the library and running away; Laravel 9 officially released | Sifu weekly
- 刷视频的功夫,不如看看这些面试题你掌握了没有,慢慢积累月入过万不是梦。
- 数字电路基础(五)算术运算电路
- 指针 --按字符串相反次序输出其中的所有字符
- The most popular colloquial system explains the base of numbers
- JDBC read this article is enough
- Function: calculates the number of uppercase letters in a string
- 四元数---基本概念(转载)
- Feature extraction and detection 14 plane object recognition
猜你喜欢
内网渗透之内网信息收集(四)
Statistics 8th Edition Jia Junping Chapter 14 summary of index knowledge points and answers to exercises after class
Intel oneapi - opening a new era of heterogeneity
Record an API interface SQL injection practice
[paper reproduction] cyclegan (based on pytorch framework) {unfinished}
《统计学》第八版贾俊平第二章课后习题及答案总结
Statistics 8th Edition Jia Junping Chapter 5 probability and probability distribution
Get started with Matplotlib drawing
SystemVerilog discusses loop loop structure and built-in loop variable I
How to earn the first pot of gold in CSDN (we are all creators)
随机推荐
Intranet information collection of Intranet penetration (2)
C language learning summary (I) (under update)
JVM memory model concept
《统计学》第八版贾俊平第三章课后习题及答案总结
Wu Enda's latest interview! Data centric reasons
Get started with Matplotlib drawing
Résumé des points de connaissance et des réponses aux exercices après la classe du chapitre 7 de Jia junping dans la huitième édition des statistiques
The difference between layer 3 switch and router
Function: find the maximum common divisor and the minimum common multiple of two positive numbers
Statistics 8th Edition Jia Junping Chapter IX summary of knowledge points of classified data analysis and answers to exercises after class
Internet Management (Information Collection)
Intranet information collection of Intranet penetration (4)
Ucos-iii learning records (11) - task management
Data mining - a discussion on sample imbalance in classification problems
《统计学》第八版贾俊平第十三章时间序列分析和预测知识点总结及课后习题答案
Record an edu, SQL injection practice
函数:用牛顿迭代法求方程的根
Captcha killer verification code identification plug-in
Hcip -- MPLS experiment
[issue 18] share a Netease go experience