当前位置:网站首页>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 .
边栏推荐
- Attack and defense world misc practice area (simplerar, base64stego, no matter how high your Kung Fu is, you are afraid of kitchen knives)
- JDBC看这篇就够了
- 《统计学》第八版贾俊平第五章概率与概率分布
- [pointer] find the length of the string
- 《统计学》第八版贾俊平第八章假设检验知识点总结及课后习题答案
- Load balancing ribbon of microservices
- Intranet information collection of Intranet penetration (5)
- {1,2,3,2,5}查重问题
- [pointer] delete all spaces in the string s
- How does SQLite count the data that meets another condition under the data that has been classified once
猜你喜欢
随机推荐
MySQL interview questions (4)
刷视频的功夫,不如看看这些面试题你掌握了没有,慢慢积累月入过万不是梦。
[pointer] delete all spaces in the string s
An unhandled exception occurred when C connected to SQL Server: system Argumentexception: "keyword not supported:" integrated
flask实现强制登陆
MySQL learning notes (stage 1)
数字电路基础(三)编码器和译码器
Intranet information collection of Intranet penetration (5)
内网渗透之内网信息收集(二)
This article explains in detail how mockmvc is used in practical work
函数:求1-1/2+1/3-1/4+1/5-1/6+1/7-…+1/n
Statistics, 8th Edition, Jia Junping, Chapter VIII, summary of knowledge points of hypothesis test and answers to exercises after class
MSF generate payload Encyclopedia
Function: find the root of the equation by Newton iterative method
Hcip -- MPLS experiment
Constants, variables, and operators of SystemVerilog usage
[paper reproduction] cyclegan (based on pytorch framework) {unfinished}
数字电路基础(一)数制与码制
Sword finger offer 23 - print binary tree from top to bottom
. Net6: develop modern 3D industrial software based on WPF (2)