python多线程

模块有两个:threading和thread

thread模块实现多线程:

a=0
def funt(no,b):
    global a
    while True:
        a+=1
        print 'thread no %d = %d' %(no,a)

def test():
    thread.start_new_thread(funt,(1,2))
    thread.start_new_thread(funt,(2,2))
    time.sleep(10)
   
if __name__=='__main__':
    test()






threading模块实现多线程:

import threading
import time

count =0
class aa(threading.Thread):
    def __init__(self, no,interval):
        threading.Thread.__init__(self)
        self.no=no
        self.interval=interval
        self.isstop=False
       
    def run(self):
        global count
        while not self.isstop:
            count+=1
            print 'thread %d-- count %d' %(self.no,count)
            time.sleep(self.interval)
           
    def stop(self):
        self.isstop=True
       
       
def factory():
    t1=aa(1,1)
    t2=aa(2,2)
    t1.start()
    t2.start()
    time.sleep(20)
    t1.stop()
    t2.stop()
   
if __name__=='__main__':
    factory()







thread模块比较简单,使用thread.start_new_thread(funt,(1,2))方法传入一个函数和参数元组即可
threading模块比较灵活,需要继承threading.Thread类,通过重写方法修改运行代码run(),线程和java类似通过t1.start()启动
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值