当前位置:网站首页>Summary of process and thread knowledge points 1
Summary of process and thread knowledge points 1
2022-07-29 01:06:00 【SnnnSn~】
Catalog
3. Difference between process and thread
4.java The relationship between threads and operating system threads
Two . Four ways to create threads
Method 2 Realization Runnable Interface
Method 3 adopt ExecutorService and Callable Interface implements a thread with a return value
Method four Thread pool based execute(), Create a temporary thread
3、 ... and . Common thread scheduling methods
3.wait(long timeout, int nanos):
2.boolean isInterrupted() ⽅ Law :
3.boolean interrupted() ⽅ Law :
One . Concept
1. What is a thread
A thread is an execution flow , Each thread can execute its own code in order , Between multiple threads “ meanwhile ” Execute multiple copies of code .
2. Why have threads
A thread is the smallest unit of program execution .
2.1“ Concurrent programming ” Become “ Just need to ”.
In order to improve computing power , Need multi-core CPU, To make the most of multicore CPU, Some tasks require “ wait for IO”, In order to allow waiting time to do some other work , You need to use parallel programming .
2.2 Compared with threads
Although multiple processes can also realize concurrent programming , But threads are lighter than processes .
- Creating threads is faster than creating processes
- Destroying threads is faster than destroying processes
- Scheduling threads is faster than scheduling processes
2.3" Thread pool "(ThreadPool) and " coroutines " (Coroutine)
Although threads are already lighter than processes , But people are not satisfied , Hence the " Thread pool " and " coroutines " .
3. Difference between process and thread
- Processes contain threads , Each process has at least one thread , The main thread
- Process is an independent unit of system resource allocation and scheduling , Thread is the smallest unit of program running
- The process has its own independent memory space address , Threads only enjoy the necessary resources for instruction flow execution , Such as : register 、 Stack
- The threads of unified processes share memory and file resources , You can communicate directly without using the kernel
- Thread creation 、 Switch . Termination is more efficient than process
4.java The relationship between threads and operating system threads
Thread is a concept in operating system . The operating system kernel implements the mechanism of thread , It also provides some for the user layer API For users to make use ( for example Linux Of pthread library ).
Java Standard library Thread Class can be considered to be provided to the operating system API Further abstraction and encapsulation are carried out .
Two . Four ways to create threads
Method 1 Inherit Thread class
1. Inherit Thread To create a thread class , Definition Thread Subclasses of classes , rewrite run Method ,run() Inside the method is the execution body of the thread .
class MyThread extends thread {
@override
public void run() {
System.out.println(" This is the code that the thread runs ");
}
}
2. establish Thread Subclass (MyThread) example
MyThread mt = new MyThread();
3. Start thread
mt.start();
public class ThreadTest {
/**
* Inherit Thread class
*/
public static class MyThread extends Thread {
@Override
public void run() {
System.out.println("This is child thread");
}
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
Method 2 Realization Runnable Interface
1. Realization Runable Interface
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(" Here is the code that the thread runs ");
}
}
2. establish Thread Class instance , call Thread The construction method of will Runnable Object as target Parameters
Thread t = new Thread(new MyRunnable());
3. call start Method
t.start();
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable!");
}
public static void main(String[] args) {
MyRunnable task = new MyRunnable();
new Thread(task).start();
}
}
Method 3 adopt ExecutorService and Callable Interface implements a thread with a return value
1. Create a class implementation Callable Interface
2. rewrite call() Method
such ⽅ The formula can be expressed by FutureTask Get task execution ⾏ The return value of
public class CallerTask implements Callable<String> {
public String call() throws Exception {
return "Hello,i am running!";
}
public static void main(String[] args) {
// Create asynchronous tasks
FutureTask<String> task=new FutureTask<String>(new CallerTask());
// Start thread
new Thread(task).start();
try {
// Waiting for execution ⾏ complete , And get the return result
String result=task.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
Method four Thread pool based execute(), Create a temporary thread
We can use the cache strategy to create threads using thread pools
Create :
(1) Creating a thread pool
(2) Call the thread pool execute() Method
(3) Methods using anonymous inner classes , establish Runnable object , And rewrite run() Method
public class EThread {
public static void main(String[] args) {
// Creating a thread pool
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for(int i = 0;i<10;i++) {
// call execute() Method to create a thread
// Methods using anonymous inner classes , establish Runnable object , And rewrite run() Method
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
}
}
3、 ... and . Common thread scheduling methods
Waiting and notifying :
stay Object class There is ⼀ Some functions can ⽤ Waiting and notification of threads .
1.wait():
When ⼀ Threads A transfer ⽤⼀ Shared variables wait()⽅ Legal time , Threads A It's going to get stuck , Hair ⽣ Next ⾯⼏ Only in this case will it return :
(1) Threads A transfer ⽤ Shared objects notify() perhaps notifyAll()⽅ Law ;
(2) Other threads call ⽤ Thread A Of interrupt() ⽅ Law , Threads A Throw out InterruptedException Exception return .
2.wait(long timeout) :
This ⽅ the aspects of things ⽐ wait() ⽅ Too much ⼀ individual Timeout parameters , The difference is , If the thread A transfer ⽤ Shared objects wait(long timeout)⽅ After the law , Not in the specified timeout ms Wake up by other threads in time , So this ⽅ Law will still be because of timeout ⽽ return .
3.wait(long timeout, int nanos):
Its internal tone ⽤ Yes. wait(long timout) function .
On ⾯ The thread waits ⽅ Law ,⽽ The wake-up thread is mainly the next ⾯ Two ⽅ Law :
4.notify() :
⼀ Threads A transfer ⽤ Shared objects notify() ⽅ After the law , Will wake up ⼀ In this shared variable ⽤ wait series ⽅ Thread suspended after method . ⼀ There may be multiple threads waiting on shared variables , Specifically Which waiting thread to wake up is random Of .
5.notifyAll() :
It is different from raising the shared variable ⽤ notify() The function wakes up the ⼀ Threads notifyAll()⽅ The law will wake up all due adjustments on the shared variable ⽤ wait series ⽅ Law ⽽ Suspended threads .
Thread class Also provided ⼀ individual ⽅ Law ⽤ Waiting ⽅ Law :
6.join():
If ⼀ Threads A Of board ⾏ 了 thread.join() sentence , Its meaning is : Current thread A wait for thread End of thread ⽌ After that, I started from thread.join() return .
Thread to sleep
1.sleep(long millis) :
Thread Class static ⽅ Law , When ⼀ Hold on ⾏ Thread in A transfer ⽤ 了 Thread Of sleep⽅ After the law , Threads A Will temporarily give up the execution of the specified time ⾏ power , But threads A Monitor resources owned ,⽐ Such as The lock is still held and cannot be surrendered . When the specified sleep time is up, the function will return normally , Then participate in CPU The scheduling , Get CPU You can continue to transport resources ⾏.
Give up the priority
1.yield() :
Thread Class static ⽅ Law , When ⼀ A thread call ⽤ yield ⽅ Legal time , It's actually dark ⽰ The thread scheduler requests the current thread to give up ⾃⼰ Of CPU , But thread scheduler Sure ⽆ The condition ignores this dark ⽰.
Thread the interrupt
Java The thread interrupt in is ⼀ A mode of collaboration between threads , By setting the interrupt flag of the thread It can't end directly ⽌ The execution of this thread ⾏,⽽ Is the interrupted thread according to the interrupt state ⾃⾏ Handle .
1.void interrupt() :
Interrupt threads , for example , When a thread A shipment ⾏ when , Threads B It can be adjusted ⽤ Threads interrupt() ⽅ Method to set the interrupt flag of the thread as true and ⽴ Return . Setting a sign is just setting a sign , Just send the message of stop sign , In fact, it does not affect the operation .
2.boolean isInterrupted() ⽅ Law :
Detect whether the current thread is interrupted .
3.boolean interrupted() ⽅ Law :
Detect whether the current thread is interrupted ,true: Let thread stop false: Didn't stop . And isInterrupted The difference is , The ⽅ If the current thread is found to be interrupted , The interrupt flag is cleared
边栏推荐
- Consumer unit
- Inftnews | yuanuniverse shopping experience will become a powerful tool to attract consumers
- 管理区解耦架构见过吗?能帮客户搞定大难题的
- Android必备的面试技能(含面试题和学习资料)
- [unity] configure unity edit C as vscode
- 双链表的定义 ~
- [web development] basic knowledge of flask framework
- Wechat campus bathroom reservation applet graduation design finished product (5) assignment
- 新一代超安全蜂窝电池,思皓爱跑上市,13.99万起售
- Wechat campus bathroom reservation of small program completion work (6) opening defense ppt
猜你喜欢
DDD领域驱动设计如何进行工程化落地
Wechat campus bathroom reservation of small program completion work (6) opening defense ppt
ThinkPHP高仿蓝奏云网盘系统程序
一元函数积分学之1__不定积分
AQS principle
将行内元素转换为块元素的方法
What are the methods to track the real-time market of London Silver?
【树莓派】widows电脑如何与树莓派连接
iNFTnews | 元宇宙购物体验将成为吸引消费者的一大利器
用CDO进行nc数据的不规则裁剪
随机推荐
[Commons lang3 topic] 001 stringutils topic
day8
Dart array, map, type judgment, conditional judgment operator, type conversion
Consumer unit 消费单元
Copy the table in word to wechat as a picture and send it
Kwai focuses on regulating the number maintenance behavior in the ways of handling and manuscript washing, and how to purify the content ecology on the we media platform
[notes for question brushing] binary linked list to integer
AQS principle
solidity实现智能合约教程(5)-NFT拍卖合约
正则表达式
SystemVerilog join and copy operators
B- 树 ~
mysql分表之后怎么平滑上线?
如何处理项目中的时间、范围和成本限制?
进程和线程知识点总结 2
【刷题笔记】链表内指定区间反转
In the second round, 1000 okaleido tiger were sold out in one hour after logging in to binance NFT again
Cloud function realizes website automatic check-in configuration details [web function /nodejs/cookie]
可视化全链路日志追踪
Main thread and daemon thread