当前位置:网站首页>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
边栏推荐
- How to reload the win10 app store?
- TensorFlow加载cifar10数据集
- Webgl and webgpu comparison [4] - uniform
- About the use of Aidl, complex data transmission
- Multiple decorators decorate a function
- Inter thread synchronization semaphore control
- Summary of 2022 spring moves of ordinary people (Alibaba and Tencent offer)
- Lifeifei's team applied vit to the robot, increased the maximum speed of planning reasoning by 512 times, and also cued hekaiming's MAE
- mysql整体架构和语句的执行流程
- flutter
猜你喜欢

Rxjs TakeUntil 操作符的学习笔记

Linux-MySQL数据库之高级SQL 语句一

Navicat Premium 15 for Mac(数据库开发工具)中文版

Uncover gaussdb (for redis): comprehensive comparison of CODIS

Go language - lock operation
Check whether the port number is occupied

Share the code technology points and software usage of socket multi client communication
Create raspberry PI image file of raspberry pie

The style of the mall can also change a lot. DIY can learn about it!

Multiple decorators decorate a function
随机推荐
Servlet详解
sql优化的几种方式
Write one file to the marked location of another file
Error: homebrew core is a shallow clone
Constructor Pattern
Uncover gaussdb (for redis): comprehensive comparison of CODIS
Read the configuration, explain the principle and read the interview questions. I can only help you here...
ES6 deconstruction assignment rename
What are the reasons why the game industry needs high defense servers?
Detailed explanation of IVX low code platform series -- Overview (I)
How to reload the win10 app store?
报错:homebrew-core is a shallow clone
Analysis of the concept of metacosmic system
Common APIs and exception mechanisms
Don't underestimate the integral mall, its role can be great!
Mixed density network (MDN) for multiple regression explanation and code example
不要小看了积分商城,它的作用可以很大!
Uniapp converts graphic verification codes in the form of file streams into images
Report on Hezhou air32f103cbt6 development board
[Third Party framework] retrofit2 (1) of network request framework -- Getting Started Guide