当前位置:网站首页>Multithreading basic part part 1
Multithreading basic part part 1
2022-06-27 05:55:00 【Gold content of Xiaobai】
Catalog
process : An execution of a program in a system
Threads : A subtask in the process
Difference between process and thread
Classes that describe Thread objects -Thread class
run Methods and start Differences in methods
Create thread :Java There are four ways to create a thread in
a. Inherit Thread class , overwrite run Method ( Ready made core task methods )
Use anonymous inner classes to create Tread Object writing
b. overwrite Runnable Interface , overwrite run Method
Use anonymous inner class to implement Runnable Interface
c. overwrite Callable Interface , overwrite call Method
d. Creating threads using thread pool
2.Thread The core properties of the class
3. The start thread calls Tread Class start Method
There are two ways to interrupt threads
There are two ways for a thread to receive a built-in interrupt notification
5. Wait for another thread -join Method
6. Get the currently executing thread object
8. Change the thread state from running state to ready state =>yield() Method
BLOCKED , WAITING , TIMED_WAITING
Processes and threads
process : An execution of a program in a system
The process is the resource allocation in the current operating system (CPU, Memory and other key system information ) Minimum unit of , Different processes are independent of each other .
This is the process in the task manager

Threads : A subtask in the process
A thread is an independent task in a process , For example, downloading the browser process , Listen to music, etc , Just some threads of the browser process
All threads of the same process share the process resources , Threads are operating system task execution ( System scheduling ) The basic unit of
Difference between process and thread
1. The process is os The basic unit of resource allocation , Thread is os The basic unit of system scheduling .
2. Creating and destroying a process is much more expensive than a thread ( The cost is equivalent to time ), Threads are lighter .
3. Scheduling a thread is also much faster than scheduling a process .( Launch the browser / Browser tags , The label must be fast )
4. The process contains threads , Each process contains at least one thread ( The main thread ).
5. Processes are relatively independent of each other , Different processes do not share memory space , Threads of the same process share memory space .
Classes that describe Thread objects -Thread class
The entrance to our program is main Method , All calls start with the main method , So the same , All thread tasks are also from the main method ( The main thread ) To begin .
Java The classes describing threads in are Thread class ——java.lang.Thread The core class of class thread , It's all through Thread Class to start a thread .
When we finish writing the subclass of the thread run Method , Invokes in the main method Thread object .start Method to start a thread .
All threads are parallel , At the same time, execute in the computer
Use jconsole Thread status can be observed , Used to compare threads
run Methods and start Differences in methods
run Method
run Method is the work task of thread class , in other words ,run Method determines what the thread does after it is started , When run Method execution completed (JVM start-up run Method ), The thread will enter the destroy state .
start Method
start The method is Thread Class to start the thread , Only thread objects call start Method will be scheduled by the system , Enter the running state .
Create thread :Java There are four ways to create a thread in
a. Inherit Thread class , overwrite run Method ( Ready made core task methods )
// Inherit Thread class
public static class Run2 extends Thread{
@Override
public void run() {
System.out.println(" Inherit Thread class ");
}
}ps: adopt Thread Class start Start thread
a Thread and startup in mode
1. A subclass inheritance Thread class
2. overwrite run Method
3. Generate the current subclass object , And then call start Method to start the thread
Use anonymous inner classes to create Tread Object writing
// Inherit inner class creation Thread object
Thread thread3 = new Thread() {
@Override
public void run() {
System.out.println(" Inheriting anonymous inner classes Thread object ");
}
};b. overwrite Runnable Interface , overwrite run Method
public static class Run implements Runnable{
@Override
public void run() {
System.out.println(" Realization Runnable Interface ");
}
}ps: adopt Thread Class start Start thread
b Thread and startup in mode
1. Realization Runnable Interface
2. overwrite run Method
3. establish Thread Class object , call start Method
Use anonymous inner class to implement Runnable Interface
// Inheriting anonymous inner classes Runnable
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(" Inheriting anonymous inner classes Runnable");
}
}," Xiao peng ");Use Lambda expression
Thread thread3 = new Thread(()-> {
System.out.println("Lambda Thread creation of expression ");
}," A Ming ");c. overwrite Callable Interface , overwrite call Method
d. Creating threads using thread pool
Thread Class
Thread Class is JVM Describes the classes that manage threads , Each thread corresponds to a unique Thread object
1. Construction method

Such as , Pass in Runnable The methods of interface classes are constructor methods
ps: The thread can be named after the interface is passed in

2.Thread The core properties of the class
A picture flow

3. The start thread calls Tread Class start Method

4. Interrupt threads
There are two ways to interrupt threads
a. Interrupt by sharing variables

b. adopt Thread.interrupted() Static methods or Thread Member method of object isInterrupted()
Thread There is a property of whether the thread is interrupted in the class

There are two ways for a thread to receive a built-in interrupt notification
a. When a thread calls sleep/wait/join When the method is blocked , Notice of interruption received thread.interrupt()
Throw interrupt exception InterruptedException
When an exception is thrown , The interrupt state of the current thread will be cleared
b. The thread does not call the above three methods , Receive interrupt notification when in normal operation state thread.interrupt()
Thread.interrupted() Determine whether the current thread is interrupted , If the interrupt status is true Clear interrupt flag

Thread.currentThread.isInterrupted(); Judge whether the specified thread object is in interrupt state , If the state is true, The interrupt flag is not cleared

5. Wait for another thread -join Method
use join Method , When a thread calls another thread's join Method , Wait until the calling thread finishes executing , To continue executing subsequent code for this thread .

join A variation of the method

6. Get the currently executing thread object
Thread.currentThread() => Get the executing thread object
for example
Thread.currentThread().getName()Thread.currentThread().isInterrupted()7. Hibernate current process
Thread.sleep(long millis) (ms) Method , Sleep the process in which it is used .
8. Change the thread state from running state to ready state =>yield() Method
call yield The thread of the method will voluntarily give up CPU resources , From running state to ready state , Waiting to be CPU Continue to dispatch .
When will you give up CPU, When was it CPU Reschedule , All are os The scheduling of , We have no choice .
There are two possibilities for this approach :
a. After the thread makes the operation in running state , Dispatch again soon
b. After the thread makes the operation in running state , Not scheduled for a long time

This method is completely controlled by CPU control , We can't control it , So I don't use much .
State of thread
Attach a status chart , The following description will rely on the following figure

NEW
New thread object ,new One Thread Object is new state
New state , It hasn't started yet

RUNNABLE
Ready and running , Thread object .start Namely RUNNABLE state
Next state , Executable state ( Really running and about to start execution , All in this state )

BLOCKED , WAITING , TIMED_WAITING
Wait state , All three waiting states are blocked ( This thread needs to suspend execution , The reasons for the suspension of execution caused by these three factors are different )
TIMED_WAITING
Overtime waiting , Indicates that the thread needs to wait for a period of time before resuming execution
for example sleep The method is this kind of waiting
BLOCKED
When a thread is locked and waiting to acquire a lock object, it is BLOCKER state

WAITING
When threads use lock.wait() When the method is used , Description: enter the thread waiting state , That requires another thread lock.notify Method to unlock this thread

TERMINATED

run Method execution completed , Or throw an exception and execute abnormally
Termination status , Indicates that the current thread has finished executing , It can be destroyed
You can use the thread object of the main thread .isAlive() Method to determine whether the thread is alive

边栏推荐
- Create a basic WDM driver and use MFC to call the driver
- 函数栈帧的形成与释放
- KubeSphere 集群配置 NFS 存储解决方案-收藏版
- [FPGA] realize the data output of checkerboard horizontal and vertical gray scale diagram based on bt1120 timing design
- Leetcode298 weekly race record
- Webrtc series - Nomination and ice of 7-ice supplement for network transmission_ Model
- STM32 reads IO high and low level status
- C# netcore中 配置帮助类IConfiguration
- NLP-D62-nlp比赛D31&刷题D15
- 双位置继电器RXMVB2 R251 204 110DC
猜你喜欢

Web3 has not been implemented yet, web5 suddenly appears!

Using domain name forwarding mqtt protocol, pit avoidance Guide

Gao Xiang slam14 lecture - note 1

STM32 reads IO high and low level status
![Senior [Software Test Engineer] learning route and necessary knowledge points](/img/51/1be2e0812a6bca9e5e8d14bf254254.png)
Senior [Software Test Engineer] learning route and necessary knowledge points

cpu-z中如何查看内存的频率和内存插槽的个数?

多线程基础部分Part2

程序猿学习抖音短视频制作

汇编语言-王爽 第9章 转移指令的原理-笔记

我对于测试团队建设的意见
随机推荐
Unity point light disappears
[FPGA] design and implementation of frequency division and doubling based on FPGA
【Cocos Creator 3.5.1】坐标的加法
Dual position relay dls-34a dc0.5a 220VDC
What is BFC? What's the usage?
Obtenir le volume du système à travers les plateformes de l'unit é
[FPGA] realize the data output of checkerboard horizontal and vertical gray scale diagram based on bt1120 timing design
C语言练手小项目(巩固加深知识点理解)
Wechat applet refreshes the current page
【QT小作】使用结构体数据生成读写配置文件代码
函数栈帧的形成与释放
Opencv implements object tracking
Netease cloud music params and encseckey parameter generation code
How JQ gets the reciprocal elements
Spark's projection
How JQ gets the ID name of an element
我对于测试团队建设的意见
汇编语言-王爽 第9章 转移指令的原理-笔记
Leetcode298 weekly race record
Some articles about component packaging and my experience