线程的两种创建方式

方式一:

import time
from threading import Thread
def sing(name):
    for i in range(3):
        print(name,'sing a song',i)
        time.sleep(1)
if __name__ == '__main__':
    name_list=['艾默生','贝多芬']
    t_list=[]
    for i in name_list:
        t=Thread(target=sing,args=(i,))
        t_list.append(t)
    for i in t_list:
        i.start()
        i.join()

方式二:类的方式

from threading import Thread
import time
import threading
class MyThread(Thread):
    def __init__(self,name):
        Thread.__init__(self)
        self.name=name
    def run(self):
        for i in range(3):
            print(self.name,'run a round:',i)
            time.sleep(0.1)
if __name__ == '__main__':
    name_list=['阿尔法','贝塔']
    t_list=[]
    for i in name_list:#实例化两个对象
        t=MyThread(i)
        t_list.append(t)#将对象添加到list中
    for i in t_list:
        i.start()
        i.join()
    print(len(threading.enumerate()))#打印当前线程数

你可能感兴趣的:(Python)