python支持两种创建多线程的方式:
thread.Thread(group=None,name='Tread-x',targt=None,args=(),kwargs={},daemon=None)
参数介绍:
语法 | 含义 |
---|---|
group | 一般不用 |
name | 线程名 |
targt | 目标函数 |
args | 目标函数的参数,数据类型:元祖。与kwargs水火不容,只存在一个参数即可 |
kwargs | 目标函数的参数,数据类型:字典。与args水火不容,只存在一个参数即可 |
daemon | 用来设置线程是否随主线程退出而退出 |
class mythread(threading.Thread)
import threading
def test_thread(arg1,arg2):
for i in range(arg1,arg2):
print(threading.current_thread().name,i)
if __name__=="__main__":
thread1 = threading.Thread(name='t1',target= test_thread,args=(1,10))
thread2 = threading.Thread(name='t2',target= test_thread,kwargs={"arg1":101,"arg2":110})
thread1.start() #启动线程1
thread2.start() #启动线程2
输出:
t1 1
t1 2
t1 3
t2 101
t1 4
t1 5
t1 6
t1 7
t1 8
t1 9
t2 102
t2 103
t2 104
t2 105
t2 106
t2 107
t2 108
t2 109
import threading
class MyThread(threading.Thread):
def __init__(self, threadName,arg1,arg2):
super(MyThread, self).__init__(name=threadName)
self.arg1=arg1
self.arg2=arg2
def run(self):
for i in range(self.arg1,self.arg2):
print(self.name, i)
if __name__=="__main__":
MyThread('t1',1,10).start() #启动线程1
MyThread('t2',101,110).start() #启动线程2
输出:
t1 1
t1 2
t1 3
t1 4
t2 101
t2 102
t1 5
t2 103
t2 104
t1 6
t2 105
t2 106
t1 7
t2 107
t1 8
t1 9
t2 108
t2 109