linux线程继承,Python继承类的方式实现多线程及控制线程数

继承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!')

运行结果:

377b8a695db76b456d97c2107fe80000.png

接着用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!')

运行结果:

d6d0241632038b4b92e1f159671fd158.png

接下来就根据需要来扩展run方法,满足日常工作。

推荐阅读:

Python 的详细介绍:请点这里

Python 的下载地址:请点这里0b1331709591d260c1c78e86d0c51c18.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值