当前位置:网站首页>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/ag3ipekE
https://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 .
边栏推荐
- [pointer] find the value of the largest element in the two-dimensional array
- Statistics 8th Edition Jia Junping Chapter 14 summary of index knowledge points and answers to exercises after class
- 数据库多表链接的查询方式
- 使用 flask_whooshalchemyplus jieba实现flask的全局搜索
- Function: find 1-1/2+1/3-1/4+1/5-1/6+1/7-... +1/n
- 数字电路基础(一)数制与码制
- Matplotlib绘图快速入门
- Functions: Finding Roots of equations
- Captcha killer verification code identification plug-in
- Overview of LNMP architecture and construction of related services
猜你喜欢
Web vulnerability - File Inclusion Vulnerability of file operation
1.支付系统
How to earn the first pot of gold in CSDN (we are all creators)
《统计学》第八版贾俊平第十章方差分析知识点总结及课后习题答案
移植蜂鸟E203内核至达芬奇pro35T【集创芯来RISC-V杯】(一)
《统计学》第八版贾俊平第四章总结及课后习题答案
New version of postman flows [introductory teaching chapter 01 send request]
MySQL中什么是索引?常用的索引有哪些种类?索引在什么情况下会失效?
关于交换a和b的值的四种方法
Solutions to common problems in database development such as MySQL
随机推荐
《统计学》第八版贾俊平第六章统计量及抽样分布知识点总结及课后习题答案
浙大版《C语言程序设计实验与习题指导(第3版)》题目集
JDBC看这篇就够了
flask实现强制登陆
Proceedingjoinpoint API use
Function: find the maximum common divisor and the minimum common multiple of two positive numbers
Attack and defense world misc practice area (simplerar, base64stego, no matter how high your Kung Fu is, you are afraid of kitchen knives)
[pointer] find the value of the largest element in the two-dimensional array
数字电路基础(三)编码器和译码器
线程的实现方式总结
Numpy Quick Start Guide
captcha-killer验证码识别插件
我的第一篇博客
Constants, variables, and operators of SystemVerilog usage
Windows platform mongodb database installation
Function: calculates the number of uppercase letters in a string
Record an edu, SQL injection practice
Chain team implementation (C language)
How does SQLite count the data that meets another condition under the data that has been classified once
数据库多表链接的查询方式