当前位置:网站首页>Day21 multithreading
Day21 multithreading
2022-06-25 16:20:00 【weixin_ forty-eight million six hundred and forty-four thousand】
- Multithreading
- Program , process , Threads
Program : A collection of commands , In order to complete the specified function , A program is a static concept , Usually stored in the hard disk
process : Running programs , It's a dynamic concept , Need to be saved in memory , The operating system assigns the corresponding PID, When we close a process directly , The process will be destroyed in the running memory
Threads : In a program , Different branches , If the same time node allows multiple threads to execute at the same time , We call it supporting multithreading
stay Java in ,main Method start execution , It's just a thread , Called the main thread
- Parallel and concurrent
parallel : Multiple CPU, Perform multiple tasks at the same time
Concurrent : One CPU, Perform multiple tasks at the same time
Multithreading parallel must CPU Be greater than or equal to 2 Talent
Single core CPU There is no multithreading
- Single core CPU Hetuohe CPU
- Single core CPU, It's actually a fake multithreading , Because in a unit of time , Only one thread can be executed The task of . for example : Although there are multiple lanes , But there is only one staff member in the toll station charging , Only charge Can pass , that CPU It's like a toll collector . If someone doesn't want to pay , Then the toll collector can Take him “ Hang up ”( Hang him , When he's figured it out , Ready for the money , Charge again ). But because CPU when The inter unit is very short , So I can't feel it .
- If it's multicore , In order to better play the efficiency of multithreading .( Today's servers are multi-core )
- One Java Applications java.exe, There are at least three threads :main() The main thread ,gc() Garbage collection thread , Exception handling threads . Of course, if something goes wrong , Will affect the main thread .
- Advantages, disadvantages and application scenarios of multithreading
background : Single core CPU For example , Only use a single thread to complete multiple tasks successively ( Call multiple parties Law ), It must take less time than using multiple threads to complete , Why is it still necessary to multithread ?
The advantages of multithreading programs :
- Improve application response . More meaningful for graphical interfaces , Enhance the user experience .
- Improving computer systems CPU Utilization ratio
- Improve program structure . Divide a long and complex process into multiple threads , Independent operation , Conducive to understanding and
modify
- Programs need to perform two or more tasks at the same time .
- When the program needs to implement some tasks that need to wait , Such as user input 、 File read and write operations 、 Network operating 、 Search, etc .
- When you need some background programs .
- Runnable Thread creation
public static void main(String[] args){ test_02(); } public static void test_02() { // Create an implementation class object Processor_01 p = new Processor_01(); // Create thread class objects Thread t1 = new Thread(p); // Start thread t1.start(); for(int i = 0; i<10 ; i++){ System.out.println("main Threads -->"+i); } } public static void test_01(){ // Create thread class objects Thread t1 = new Processor(); // call start Method Start thread t1.start(); for(int i = 0;i<10;i++){ System.out.println("main Threads -->"+i); } } } /** * The first one is Create a class , Inherit Thread class And overwrite run Method * * run Method It's like... In a new thread main Method */ class Processor extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(" Test thread -->" + i); } } } /** * The second kind Create a class , Realization Runnable Interface , And overwrite run Method * * run Method It's like... In a new thread main Method * */ class Processor_01 implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(" Test thread -->" + i); } }
- The difference between inheritance and Implementation
public class Thread extends Object implements Runnable
- difference
- Inherit Thread: Thread code storage Thread Subclass run In the method .
- Realization Runnable: The thread code exists in the subclass of the interface run Method .
- The benefits of the implementation
- The limitation of single inheritance is avoided
- Multiple threads can share objects of the same interface implementation class , Perfect for multiple identical lines To deal with the same resource .
- Priorities and common methods
- Priority Overview
- Priorities and common methods
The priority level of the thread
- MAX_PRIORITY:10
- MIN _PRIORITY:1
- NORM_PRIORITY:5
Methods involved
- getPriority() : Returns the thread priority value
- setPriority(int newPriority) : Change the priority of a thread
explain
- Inherits the priority of the parent thread when the thread is created
- Low priority is only a low probability of obtaining scheduling , It doesn't have to be called after a high priority thread
- Runnable Thread creation
/**
* getName : Get the name of the thread
*
* setName : Set the name of the thread , If not set , The default is Thread-0 Start In turn, increasing
*
* setPriority() : set priority ,java There is 1-10 ,10 Two priority levels
* MIN_PRIORITY = 1
* NORM_PRIORITY = 5
* MAX_PRIORITY = 10
*
* getPriority() : Get priority level
*
* static currentThread() : Get the current thread object
*
* static sleep() : Put the current thread to sleep
*
* currentThread and sleep It's a static method , signify It has nothing to do with which object to call
*
* currentThread : In which thread , Just get the object of which thread
* sleep : In which thread , Just sleep on which thread , Parameter is long Type of milliseconds
*/
public class Thread_02_Priority {
public static void main(String[] args){
// Creating thread objects
Thread t1 = new Processer();
// Set the name
t1.setName("t1");
// Set the priority to 10
t1.setPriority(10);
// Set up main The priority of 1
Thread.currentThread().setPriority(1);
// Start thread
t1.start();
for (int i = 0; i < 10; i++) {
try {
// sleep 500 millisecond
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Get the thread object and get the thread name
System.out.println(Thread.currentThread().getName()+"-->"+i);
}
}
}
class Processer extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+i);
}
}
}
- Life cycle
JDK of use Thread.State Class defines several states of a thread
To achieve multithreading , A new thread object must be created in the main thread .Java Language use Thread class And its subclasses to represent threads , In its whole life cycle, it usually goes through the following 5、 ... and States :
newly build : When one Thread When an object of class or its subclass is declared and created , The new thread object is in the new state state
be ready : The thread in the newly created state is start() after , Will enter the thread queue to wait CPU Time slice , At this point, it has the conditions to run , It's just not assigned to CPU resources
function : When the ready thread is scheduled and gets CPU Resource time , It goes into operation , run() Method defines the line The operation and function of the program
Blocking : In some special case , When an I / O operation is suspended or executed artificially , Give up CPU And temporarily suspend their own execution , Go into blocking mode
Death : The thread has completed all its work or the thread has been forced to terminate ahead of time or an exception has occurred leading to the end of the thread
- Thread stop
/**
* stop : Terminate no thread execution , This method is out of date , It is not recommended to use , Because it may cause deadlock
*
* Therefore, identifiers are generally used to solve
*
*/
public class Thread_03_Stop {
public static void main(String[] args) {
Processer_03 p = new Processer_03();
Thread t1 = new Thread(p);
t1.setName("t1");
t1.start();
try {
Thread.sleep(5000);
// t1.stop();
p.flag=true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Processer_03 implements Runnable {
// Add a logo , Identify whether to terminate the thread
boolean flag = false;
@Override
public void run() {
for (int i = 0; true; i++) {
// Judge whether to terminate
if (flag) {
System.out.println(Thread.currentThread().getName() + " Thread terminated ");
return;
}
try {
Thread.sleep(1000);
System.out
.println(Thread.currentThread().getName() + "-->" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
- Thread merge
/** * join : Thread merge , Let the current thread wait for the specified thread to finish executing , And go on with it */ public class Thread_04_Join { public static void main(String[] args) throws InterruptedException { Thread t1 = new Processer_04(); t1.setName("t1"); t1.start(); // Come here ,main Just wait t1 After the thread has finished executing , And go on with it t1.join(); for (int i = 0; i < 10; i++) { try { // sleep 500 millisecond Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } // Get the thread object and get the thread name System.out.println(Thread.currentThread().getName() + "-->" + i); } } } class Processer_04 extends Thread { @Override public void run() { for (int i = 0; i < 10; i++) { try { // sleep 500 millisecond Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } // Get the thread object and get the thread name System.out.println(Thread.currentThread().getName() + "-->" + i); } } }
Yield
/** * yield : Static methods , Pause the currently executing thread object , And execute other waiting threads * * 1 Static methods , It means that there is no official thanks for calling with that object , In which thread is it written , Which thread gives way * * 2 Give way to the same priority , Different priorities do not give way */ public class Thread_05_Yield { public static void main(String[] args) { // Create thread Thread t1 = new Thread(new Processor_05()); t1.setName("t1"); // Set up t1 Threads and main Consistent thread priority t1.setPriority(5); Thread.currentThread().setPriority(5); // start-up t1.start(); for (int i = 0; i < 10; i++) { // Abdication Thread.yield(); System.out.println(Thread.currentThread().getName()+"-->"+i); } } } class Processor_05 implements Runnable{ @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+"-->"+i); } } }
Thread synchronization : When multiple threads may operate on the same data at the same time , To ensure data consistency , Synchronous execution is required
*
* The essence is to synchronize data , It's a security mechanism
*
* Asynchronous programming : Threads are completely independent , There is no influence on each other
*
* Synchronous programming : Threads are not completely independent , There may be mutual influences
*
* Synchronized scenes : 1 Must be multithreaded ( There must be concurrency , It's possible to make mistakes ) 2 The possibility that multiple threads may operate on the same data at the same time 3
* Especially when changing data at the same time , Query doesn't matter- Thread synchronization
- summary
- Thread synchronization
Problem presentation
The uncertainty of multi thread execution causes the instability of execution result
Sharing of ledger by multiple threads , This will result in incomplete operation , It will destroy the data
边栏推荐
猜你喜欢
《睡眠公式》:怎么治睡不好?
揭秘GaussDB(for Redis):全面对比Codis
Precautions for function default parameters (formal parameter angle)
Share the code technology points and software usage of socket multi client communication
Nsurlsession learning notes (III) download task
Create raspberry PI image file of raspberry pie
The release of autok3s v0.5.0 continues to be simple and friendly
B站付费视频使up主掉粉过万
一行代码可以做什么?
Lecun predicts AgI: big model and reinforcement learning are both ramps! My "world model" is the new way
随机推荐
Principle analysis of ThreadLocal source code
Free books! AI across the Internet paints old photos. Here is a detailed tutorial!
f_read 函数[通俗易懂]
Detailed explanation of IVX low code platform series -- Overview (I)
一文带你搞懂 JWT 常见概念 & 优缺点
Vscode有什么好用的插件?
Converting cifar10 datasets
合宙Air32F103CBT6開發板上手報告
AutoK3s v0.5.0 发布 延续简约和友好
[Third Party framework] retrofit2 (1) of network request framework -- Getting Started Guide
Go development team technical leader Russ Cox sends a document to share go's version control history
Process control and method
mysql整体架构和语句的执行流程
Consumer and producer cases of inter thread synchronization (condition variable)
Advanced SQL statement 1 of Linux MySQL database
NFT元宇宙发展能做什么?
The database records are read through the system time under the Android system, causing the problem of incomplete Reading Records!
js 给元素添加自定义属性
不要小看了积分商城,它的作用可以很大!
Mt60b1g16hc-48b:a micron memory particles FBGA code d8bnk[easy to understand]