VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python3基础之python使用多线程(3)

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
import threading
from time import sleep, ctime
# 创建 Thread 的实例,传给它一个可调用的类实例
# 子类的构造函数必须先调用其基类的构造函数
# 特殊方法__call__()在 子类中必须要写为 run()
loops = [32111]
class MyThread(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args
    def run(self):
        self.func(*self.args)
def loop(i, nsec):
    print(f'start loop {i} at: {ctime()}')
    sleep(nsec)
    print(f'end loop {i} at: {ctime()}')
def main():
    print('start at', ctime())
    threads = []
    nloops = range(len(loops))
    for in nloops:
        = MyThread(loop, (i, loops[i]), loop.__name__)
        threads.append(t)
    for in nloops: # start threads
        threads[i].start()
    for in nloops: # wait for all
        threads[i].join() # threads to finish
    print(f'all done at: {ctime()}')
if __name__ == '__main__':
    main()

相关教程