python中threading模块中最重要的Tread类

      Tread是threading模块中的重要类之一,可以使用它来创造线程。其具体使用方法是创建一个threading.Tread对象,在它的初始化函数中将需要调用的对象作为初始化参数传入。

      具体代码如下:

          

import threading ,time
count = 0
#在程序中,每个线程被赋予了一个名字,然后设置没隔0.3秒打印出本线程计数,即加1。
# 而count被人为地设置成全局变量,因此在每个线程中都可以自由地对其进行访问
#其中的run方法和start方法并不是threading自带的方法,而是从python本身线程处理模块Thread中继承来的,
# run方法的作用是在线程被启用以后执行预先写入的程序代码。
#一般而言,run方法所执行的内容被称为Activity;而start方法是用于启动线程的方法
class Mythread(threading.Thread):
    def __init__(self,threadName):
        super(Mythread,self).__init__(name=threadName)
    def run(self):
        global count
        for i in range(5):
            count +=1
            time.sleep(0.3)
            print(self.getName(),count)
for i in range(2):
    Mythread("MythreadName:"+str(i)).start()

   在程序中,每个线程赋予了一个名字,然后设置每隔0.3秒打印输出本线程的计数,即计数加1.而count被人为设置成全局共享变量,因此在每个线程中都可以自由地对其进行访问。

   程序运行结果如下:

    

posted @ 2019-05-16 23:21  朦胧的老狐狸  阅读(434)  评论(0编辑  收藏  举报