Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 42c6965

Browse filesBrowse files
committed
update
1 parent d63e5ba commit 42c6965
Copy full SHA for 42c6965

File tree

Expand file treeCollapse file tree

5 files changed

+9
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

5 files changed

+9
-0
lines changed
Open diff view settings
Collapse file
447 KB
  • Display the source diff
  • Display the rich diff
Loading
Collapse file
337 KB
  • Display the source diff
  • Display the rich diff
Loading
Collapse file
213 KB
  • Display the source diff
  • Display the rich diff
Loading
Collapse file
213 KB
  • Display the source diff
  • Display the rich diff
Loading
Collapse file

‎python threading 中的一些注意点.md‎

Copy file name to clipboardExpand all lines: python threading 中的一些注意点.md
+9Lines changed: 9 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,18 @@ Daemon 是古希腊神话中人们的守护者精灵之类的角色,伴随着
4343

4444
![](img/pythonThreading/daemon-exit.png)
4545

46+
![Xnip2022-04-01_14-23-21](python threading 中的一些注意点.assets/Xnip2022-04-01_14-23-21.jpg)
4647

48+
![Xnip2022-04-01_14-21-52](python threading 中的一些注意点.assets/Xnip2022-04-01_14-21-52.jpg)
4749

4850
**同时使用join()和setDaemon()方法**
4951

5052
用了join()方法,主线程会等子线程结束或超时,控制的是主线程的行为;而用了setDaemon(True)方法,主线程结束时子线程会被强制结束,控制的是子线程的行为。
5153

5254
当同时使用setDaemon(True)方法和join()方法时。可以实现:主线程给子线程足够的时间去完成任务,也能在主线程退出时让子线程也结束,能更好的控制子线程的行为。
5355

56+
57+
5458
```python
5559
# !/usr/bin/env python
5660
# -*- coding:utf-8 -*-
@@ -91,6 +95,8 @@ except KeyboardInterrupt as e:
9195

9296
类似的Java代码举例,Java中可以用Interrupt来强制结束主线程(python中没有对应的方法,目前已知的就是:关闭程序、设置join超时时间)。在Java中同时使用setDaemon(true)和join()方法,可以随时暴力干掉所有主线程和子线程。
9397

98+
99+
94100
```java
95101
package test;
96102

@@ -102,6 +108,7 @@ public class threadExampleForceStop extends Thread{
102108
xxx.start();
103109
Thread.sleep(1*60);
104110
xxx.interrupt();
111+
Thread.sleep(10*60);//如果jvm不退出,Daemon线程还是会继续执行!!!
105112
}
106113

107114
@Override
@@ -165,7 +172,9 @@ class Producertest extends Thread {
165172

166173
![daemon-and-join-java](img/pythonThreading/daemon-and-join-java.png)
167174

175+
注意!!!:如果JVM不退出,Daemon子线程还是会继续执行!只有当主线程退出时,JVM也同时退出时,Daemon子线程才会被终止。在这种情况下想要正确结束子线程,还是需要有自己的的控制逻辑!
168176

177+
![](python threading 中的一些注意点.assets/image-20220401151827722-8797641.png)
169178

170179

171180

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.