python多线程

1. 使用Thread类创建

# 导入Python标准库中的Thread模块 
from threading import Thread 
import time, random
# 线程任务函数
def thread_handle(data):
    print('thread{} is start'.format(data))
    for i in range(10):
        _time = random.random()
        print('thread%s is excute in step %d for time %f' % (data,i,_time))
        time.sleep(_time)
    print('thread%s is end' % data)

# 创建一个线程 
t1 = Thread(target=thread_handle, args=('1',)) 
t2 = Thread(target=thread_handle, args=('2',)) 
# 启动刚刚创建的线程 
t1.start()
t2.start()

t1.join()
t2.join()

print('main thread end')

2. 使用继承类创建

from threading import Thread

class MyThread(Thread):
    def __init__(self, param):
        Thread.__init__(self)
        self.param = param

    def run(self):
        print('%s is running' % self.param)

t1 = MyThread('thread1')
t2 = MyThread('thread2')
t1.start()
t2.start()

线程等待

# 只需要增加一句代码
t.join()
thread_list = [] 
for i in range(1, 11): 
  t = MyThread(parameter1) 
  thread_list.append(t) 
  t.start() 
q# 在这里统一执行线程等待的方法 
for t in thread_list: 
  t.join()

参考文章

你可能感兴趣的:(python多线程)