"""方法一:子线程的创建与启动之直接实例化Thread"""
"""
标准库模块mthreading提供了一个类对象Thread,用于表示线程
使用类对象Thread创建并启动子线程的第1种方式为:
1、根据类对象Thread创建线程实例对象
2、调用线程实例对象方法start()启动线程
调用方法start后,会自动调用run(),方法run会自动调用参数target指定的函数
"""
from threading import Thread, current_thread
import time
def do_sth(arg1, arg2):
print(‘子线程启动(%s)‘ % current_thread().getName())
time.sleep(20)
print(‘arg1=%d, arg2=%d‘ %(arg1, arg2))
print(‘子线程结束(%s)‘ % current_thread().getName())
print(‘父线程启动(%s)‘ % current_thread().getName())
thread = Thread(target=do_sth, args=(5, 8), name=‘mythread‘)
thread.start()
time.sleep(40)
print(‘父线程结束(%s)‘% current_thread().getName())
############################################################################
"""方法二:子线程的创建与启动之继承Thread"""
"""
使用类对象thread创建并启动子线程的第2种方式:
1、自定义继承Thread的类对象,重写方法__init__()和run()
2、根据自定义的类对象创建线程实例对象
3、调用线程实例对象的方法start()启动线程
这里会自动调用重写后的run()方法
"""
from threading import Thread, current_thread
import time
class Mythread(Thread):
def __init__(self, name, args):
super().__init__(name=name)
self.args = args
def run(self):
print(‘子线程启动(%s)‘ % current_thread().getName())
time.sleep(20)
print(‘arg1=%d, arg2=%d‘ % self.args)
print(‘子线程结束(%s)‘ % current_thread().getName())
print(‘父线程启动(%s)‘ % current_thread().getName())
mt = Mythread(name=‘mythread‘, args=(5,8))
mt.start()
time.sleep(20)
print(‘父线程结束(%s)‘ % current_thread().getName())
原文:https://www.cnblogs.com/sruzzg/p/12991867.html