多线程-threading.Thread

来源:互联网 发布:sql sever 视图创建 编辑:程序博客网 时间:2024/05/21 15:40

线程中的全局变量是不安全的,局部变量是安全的,各自线程保有。

查看线程数量:

length = len(threading.enumerate())

方式一:

import threading    from time import sleep    def test(sleepTime):        num=1        sleep(sleepTime)        num+=1        print('---(%s)--num=%d'%(threading.current_thread(), num))    t1 = threading.Thread(target = test,args=(5,))    t2 = threading.Thread(target = test,args=(1,))    t1.start()    t2.start()

方式二:

 #coding=utf-8    import threading    import time    class MyThread(threading.Thread):        # 重写 构造方法        def __init__(self,num,sleepTime):            threading.Thread.__init__(self) #重写父类的初始化方法            self.num = num            self.sleepTime = sleepTime        def run(self):            self.num += 1            time.sleep(self.sleepTime)            print('线程(%s),num=%d'%(self.name, self.num))    if __name__ == '__main__':        t1 = MyThread(100,5)        t1.start()        t2 = MyThread(200,1)        t2.start()


原创粉丝点击