Skip to content

Commit 0b50614

Browse files
committed
使用thread模块
1 parent d4f6f07 commit 0b50614

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
import time
3+
from threading import Thread
4+
5+
6+
class CountDownTask:
7+
def __init__(self):
8+
self._running = True
9+
10+
def terminate(self):
11+
self._running = False
12+
13+
def run(self, n):
14+
while self._running and n > 0:
15+
print('T-minus', n)
16+
n -= 1
17+
time.sleep(5)
18+
19+
20+
c = CountDownTask()
21+
t = Thread(target=c.run, args=(10,))
22+
t.start()
23+
c.terminate() # Signal termination
24+
t.join() # Wait for actual termination (if needed)
25+
print("=====end=====")
26+
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Code to execute in an independent thread
2+
import time
3+
from threading import Thread
4+
5+
6+
def countdown(n):
7+
while n > 0:
8+
print("T-minus: {}".format(n))
9+
n -= 1
10+
time.sleep(10)
11+
12+
13+
14+
if __name__ == '__main__':
15+
# 1. create a thread
16+
t = Thread(target=countdown, args=(10,))
17+
# t = Thread(target=countdown, args=(10,), daemon=True) # 将当前线程设置为后台线程,后台线程会在主线终止时自动销毁
18+
# 2 start a thread
19+
t.start()
20+
# 3 thread state
21+
# while True:
22+
# if t.is_alive():
23+
# print("Still running\n")
24+
# time.sleep(3)
25+
# else:
26+
# print('Completed\n')
27+
# break
28+
#t.join()
29+
30+
31+

0 commit comments

Comments
 (0)