Python 创建线程的方法
-
使用的是 threading 模块
-
代码如下:
1 #!/usr/bin/python3
2
3 import threading
4 import time
5
6 exitFlag = 0
7 // 创建线程的类
8 class myThead (threading.Thread):
9 def __init__(self, threadID, name, counter):
10 threading.Thread.__init__(self)
11 self.threadID = threadID
12 self.name = name
13 self.counter = counter
14 def run(self):
15 threadLock.acquire(); // 线程同步
16 print("start function : "+ self.name)
17 print_time(self.name, self.counter, 5)
18 print("exit function :" + self.name)
19 threadLock.release() // 线程同步释放
20
21 // 线程调用的函数
22 def print_time(threadName, delay, counter):
23 while counter:
24 if exitFlag:
25 threadName.exit()
26 time.sleep(delay)
27 print ("%s : %s" % (threadName, time.ctime(time.time())))
28 counter -= 1
29
30 threadLock = threading.Lock()
31 threads = []
32
33 thread1 = myThead(1, "Thread-1", 1); // 创建线程的实体
34 thread2 = myThead(2, "Thread-2", 2);
35 thread3 = myThead(3, "Thread-3", 3);
36
37 thread1.start()
38 thread2.start()
39 thread3.start()
40
41 threads.append(thread1); // 加入线程数组
42 threads.append(thread2);
43 threads.append(thread3);
44
45 for t in threads:
46 t.join(); // 线程执行
47
48 print("exit main process");
49
Read The Fucking Source Code