python-线程的简单创建

python也可以同时多任务进行

先来一个简单的创建线程

import time
import threading


# 创建三个方法
def firstThreading():
    time.sleep(5)
    ti = time.strftime("%Y%m%d %H:%M:%S")
    print('这是第一个  启动时间' + ti)


def secondThreading():
    time.sleep(5)
    ti = time.strftime("%Y%m%d %H:%M:%S")
    print('这是第二个  启动时间' + ti)


def threeThreading():
    time.sleep(5)
    ti = time.strftime("%Y%m%d %H:%M:%S")
    print('这是第三个  启动时间' + ti)


# 创建线程池
threads = []

# 创建线程
t1 = threading.Thread(target=firstThreading, name='Thread-1', )

# 把线程装进线程池
threads.append(t1)

# 再创建一个线程
t2 = threading.Thread(target=secondThreading, name='Thread-2')

# 再t2装进线程池
threads.append(t2)

# 创建第三个线程
t3 = threading.Thread(target=threeThreading, name='Thread-3')

# 把第三个线程装进线程池
threads.append(t3)



if __name__ == '__main__':
    # 计算时间
    start = time.perf_counter()
    # 运行线程池里面的线程
    for t in threads:
            t.setDaemon(True)
            t.start()
    t.join()
    end = time.perf_counter()
    print("The function run time is : %.03f seconds" % (end - start))
复制代码

运行结果:
这是第一个 启动时间20210923 15:12:40
这是第三个 启动时间20210923 15:12:40
这是第二个 启动时间20210923 15:12:40
The function run time is : 5.002 seconds

下次可以尝试这用这个多线程进行并发