标题: [技术讨论] 学习Python多线程,同时打印多个文件内容 [打印本页]
作者: Gin_Q 时间: 2020-5-27 14:55 标题: 学习Python多线程,同时打印多个文件内容
- #!/usr/bin/env python3
- #coding=utf-8
-
- from time import time
- import threading
- #列表长度觉得开启线程数量
- loops = ['1.txt','2.txt']
-
- #派生Thread的子类
- class threadFunc(threading.Thread):
- def __init__(self,func,args,name=''):
- threading.Thread.__init__(self)
- self.func = func
- self.args = args
- self.name = name
- def run(self):
- self.func(*self.args)
-
- def loop(name):
- with open(name,'r') as f:
- for line in f:
- if '\n' in line:
- print (name,' :',line,end='')
- else:
- print (name,' :',line)
-
- def main():
- print('starting at:',time())
- #线程锁
- threadkey = []
- nloops = range(len(loops))
-
- for i in nloops:
- #get线程锁
- #创建子类的实例
- t = threadFunc(loop,(loops[i],),loop.__name__)
- threadkey.append(t)
-
- #开启线程
- for i in nloops:
- threadkey[i].start()
- #等待所有线程结束
- for i in nloops:
- threadkey[i].join()
-
- print('All Done at:',time())
-
- if __name__ == '__main__':
- main()
复制代码
- starting at: 1590562220.892479
- 1.txt : 1005495524----a111111
- 1.txt : 1005495524----abc123
- 2.txt : 1111qqqq1111---a111111
- 1.txt : 1005495524----aini1314
- 2.txt : 1111qqqq1111---abc123
- 1.txt : 1005495524----iloveyou
- 2.txt : 1111qqqq1111---aini1314
- 1.txt : 1005495524----q1w2e3r4
- 2.txt : 111qqq111---a111111
- 1.txt : 1005495524----qq123123
- 2.txt : 111qqq111---abc123
- 2.txt : 111qqq111---aini1314
- All Done at: 1590562220.892479
-
- 请按任意键继续. . .
复制代码
欢迎光临 批处理之家 (http://bbs.bathome.net/) |
Powered by Discuz! 7.2 |