
1、直接通过初始化thread对象创建:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #coding=utf-8
import threading,time
def test():
t = threading.currentThread() # 获取当前子线程对象
print t.getName() # 打印当前子线程名字
i=0
while i<10:
print i
time.sleep(1)
i=i+1
m=threading.Thread(target=test,args=(),name= '循环子线程' ) #初始化一个子线程对象,target是执行的目标函数,args是目标函数的参数,name是子线程的名字
m.start()
t=threading.currentThread() #获取当前线程对象,这里其实是主线程
print t.getName() #打印当前线程名字,其实是主线程名字
|
2、通过基础thread类来创建,需要创建一个自定义线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import threading,time
class myThread (threading.Thread): #创建一个自定义线程类mythread,继承Thread
def __init__(self,name):
"" "
重新init方法
:param name: 线程名
" ""
super (myThread, self).__init__(name=name)
# self.lock=lock
print '线程名' +name
def run(self):
"" "
重新run方法,这里面写我们的逻辑
:return:
" ""
i=0
while i<10:
print i
time.sleep(1)
i=i+1
if __name__== '__main__' :
t=myThread( 'mythread' )
t.start()
|
以上就是threading在python中创建线程的两种方式,希望能对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。