Several ways to create a python thread

Use the Thread class is created

import threading
from time import sleep,ctime

def sing():
    for i in range(3):
        print("正在唱歌...%d"%i)
        sleep(1)

def dance():
    for i in range(3):
        print("正在跳舞...%d"%i)
        sleep(1)

if __name__ == '__main__':
    print('---开始---:%s'%ctime())

    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)

    t1.start()
    t2.start()

    #sleep(5) # 屏蔽此行代码,试试看,程序是否会立马结束?
    print('---结束---:%s'%ctime())
"""
输出结果:
---开始---:Sat Aug 24 08:44:21 2019
正在唱歌...0
正在跳舞...0---结束---:Sat Aug 24 08:44:21 2019
正在唱歌...1
正在跳舞...1
正在唱歌...2
正在跳舞...2
"""

Description: The main thread will wait for the end after the end of all the sub-threads

Use subclassing Thread

To make the package of each thread is more perfect, so when using the threading module, tend to define a new subclass of class, just inherit threading.Thread on it, then override the run method.

import threading
import time

class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字
            print(msg)


if __name__ == '__main__':
    t = MyThread()
    t.start()
"""
输出结果:
I'm Thread-5 @ 0
I'm Thread-5 @ 1
I'm Thread-5 @ 2
"""

Creates a thread pool ThreadPoolExecutor

from concurrent.futures import ThreadPoolExecutor
import time
import os


def sayhello(a):
    for i in range(10):
        time.sleep(1)
        print("hello: " + a)


def main():
    seed = ["a", "b", "c"]
    # 最大线程数为3,使用with可以自动关闭线程池,简化操作
    with ThreadPoolExecutor(3) as executor:
        for each in seed: 
            # map可以保证输出的顺序, submit输出的顺序是乱的
            executor.submit(sayhello, each)

    print("主线程结束")


if __name__ == '__main__':
    main()

Guess you like

Origin www.cnblogs.com/lxy0/p/11403555.html