python3有threading和_thread两种线程写法,推荐使用threading。

开多线程就是为了使用多线程的异步能力来同时执行多个线程。

1. threading方法:

以下代码可以执行异步或者同步线程。

1 import threading
 2 import time
 3  
 4  
 5 class my_thread(threading.Thread):
 6     def __init__(self, th_id, th_name):
 7         threading.Thread.__init__(self)
 8         self.th_id = th_id
 9         self.th_name = th_name
10         pass
11  
12     def run(self):
13         print("开始线程:" + self.th_name)
14         run_func(self.th_name)
15         print("退出线程:" + self.th_name)
16  
17     pass
18  
19  
20 exitFlag = 0
21  
22  
23 def run_func(th_name):
24     if exitFlag:
25         th_name.exit()
26         pass
27     else:
28         # print('运行线程:' + th_name)
29         do(th_name)
30         pass
31     print('---%s---' % (time.ctime(time.time())))
32     # time.sleep(0.1)
33     pass
34  
35  
36 # 自定义,在此定义你要运行的参数
37 def do(th_name):
38     print('---执行自定义函数---')
39  
40     pass
41  
42  
43 def index(sync):
44     print('开始创建线程。。')
45     for create in range(0, 2000):
46         # 创建新线程
47         th = my_thread(create, "Thread-" + str(create))  # id, name
48         th.start()
49         if sync:  # 线程同步异步开关,True/False
50             th.join()  # 线程等待,执行完才能进入下一个线程
51             pass
52         else:  # 异步,推荐
53             pass
54         pass
55     print('\n所有线程创建完毕。。')
56     pass
57  
58  
59 index(False)  # 同步线程True,异步线程False(推荐)

2. _thread方法(程序要求不高的话推荐这种老写法):

1 import _thread
 2  
 3  
 4 all_thread_num = 0
 5  
 6  
 7 def page_class(cla, that_num):
 8     print("已启动线程=" + str(that_num))
 9     global all_thread_num
10     all_thread_num += 1
11     print("线程总数=" + str(all_thread_num))
12     for page in range(1, 30):
13         print("内=" + str(page))
14         pass
15     pass
16  
17  
18 for cla in range(20190, 20291):  # 创建线程
19     try:
20         _thread.start_new_thread(page_class, (cla, (cla - 20000)))
21         pass
22     except:
23         print("无法启动线程")
24         pass
25     pass
26  
27 while 1:
28     pass