歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python繼承類的方式實現多線程及控制線程數

Python繼承類的方式實現多線程及控制線程數

日期:2017/3/1 9:51:16   编辑:Linux編程

繼承threading.Thread,並重寫run方法實現多線程,這裡用到logging日志模塊是為了輸出好看一些,直接print的話會幾行疊在一起,不好看:
#!/usr/bin/python
#coding:utf-8
import threading
import datetime
import logging
import time
logging.basicConfig(level = logging.DEBUG,format='(%(threadName)-10s) %(message)s',)
list = ['192.168.1.1','192.168.1.2']
class Test(threading.Thread):
def __init__(self,ip):
threading.Thread.__init__(self)
self.ip = ip

def run(self):
logging.debug("%s start!" % self.ip)
time.sleep(5)
logging.debug('%s Done!' % self.ip)


if __name__ == "__main__":
#啟動線程
for ip in list:
t = Test(ip)
t.start()
#等待所有線程結束
for t in threading.enumerate():
if t is threading.currentThread():
continue
t.join()

logging.debug('Done!')

運行結果:

接著用Semaphore去控制線程數:
#!/usr/bin/python
#coding:utf-8
import threading
import datetime
import logging
import time
logging.basicConfig(level = logging.DEBUG,format='(%(threadName)-10s) %(message)s',)
list = ['192.168.1.1','192.168.1.2']
class Test(threading.Thread):
def __init__(self,threadingSum, ip):
threading.Thread.__init__(self)
self.ip = ip
self.threadingSum = threadingSum

def run(self):
with self.threadingSum:
logging.debug("%s start!" % self.ip)
time.sleep(5)
logging.debug('%s Done!' % self.ip)


if __name__ == "__main__":
#設置線程數
threadingSum = threading.Semaphore(1)

#啟動線程
for ip in list:
t = Test(threadingSum,ip)
t.start()
#等待所有線程結束
for t in threading.enumerate():
if t is threading.currentThread():
continue
t.join()

logging.debug('Done!')

運行結果:

接下來就根據需要來擴展run方法,滿足日常工作。

Copyright © Linux教程網 All Rights Reserved