-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy paththread_3.py
More file actions
45 lines (35 loc) · 1.01 KB
/
thread_3.py
File metadata and controls
45 lines (35 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import threading
import time
class MyThread (threading.Thread):
def __init__(self, thread_id, name, counter):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.counter = counter
def run(self):
print ("开启线程: " + self.name)
# 获取锁,用于线程同步
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 释放锁,开启下一个线程
threadLock.release()
def print_time(thread_name, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (thread_name, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
# 创建新线程
thread2 = MyThread(2, "Thread-2", 2)
thread1 = MyThread(1, "Thread-1", 1)
# 开启新线程
thread2.start()
thread1.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
t.join()
print("退出主线程")