Board logo

标题: [技术讨论] 学习Python多线程,同时打印多个文件内容 [打印本页]

作者: Gin_Q    时间: 2020-5-27 14:55     标题: 学习Python多线程,同时打印多个文件内容

  1. #!/usr/bin/env python3
  2. #coding=utf-8
  3. from time import time
  4. import threading
  5. #列表长度觉得开启线程数量
  6. loops = ['1.txt','2.txt']
  7. #派生Thread的子类
  8. class threadFunc(threading.Thread):
  9.     def __init__(self,func,args,name=''):
  10.         threading.Thread.__init__(self)
  11.         self.func = func
  12.         self.args = args
  13.         self.name = name
  14.     def run(self):
  15.         self.func(*self.args)
  16. def loop(name):
  17.     with open(name,'r') as f:
  18.         for line in f:
  19.             if '\n' in line:
  20.                 print (name,' :',line,end='')
  21.             else:
  22.                 print (name,' :',line)
  23.    
  24. def main():
  25.     print('starting at:',time())
  26.     #线程锁
  27.     threadkey = []
  28.     nloops = range(len(loops))
  29.    
  30.     for i in nloops:
  31.         #get线程锁
  32.         #创建子类的实例
  33.         t = threadFunc(loop,(loops[i],),loop.__name__)
  34.         threadkey.append(t)
  35.    
  36.     #开启线程
  37.     for i in nloops:
  38.         threadkey[i].start()
  39.     #等待所有线程结束
  40.     for i in nloops:
  41.         threadkey[i].join()
  42.         
  43.     print('All Done at:',time())
  44.    
  45. if __name__ == '__main__':
  46.     main()
复制代码
  1. starting at: 1590562220.892479
  2. 1.txt  : 1005495524----a111111
  3. 1.txt  : 1005495524----abc123
  4. 2.txt  : 1111qqqq1111---a111111
  5. 1.txt  : 1005495524----aini1314
  6. 2.txt  : 1111qqqq1111---abc123
  7. 1.txt  : 1005495524----iloveyou
  8. 2.txt  : 1111qqqq1111---aini1314
  9. 1.txt  : 1005495524----q1w2e3r4
  10. 2.txt  : 111qqq111---a111111
  11. 1.txt  : 1005495524----qq123123
  12. 2.txt  : 111qqq111---abc123
  13. 2.txt  : 111qqq111---aini1314
  14. All Done at: 1590562220.892479
  15. 请按任意键继续. . .
复制代码





欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2