python多线程

来源:互联网 发布:算命准吗 知乎 编辑:程序博客网 时间:2024/05/29 10:19
模块有两个: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()启动
原创粉丝点击