实例化一个threading.Thread的对象,并传入一个初始化函数对象(initial function )作为线程执行的入口;
继承threading.Thread,并重写run函数;
方式1:创建threading.Thread对象
def printHello():
while True:
print("This is the hello threading...")
time.sleep(1)
def printNihao():
while True:
print("This is the Nihao threading...")
time.sleep(2)
if __name__ == '__main__':
t1 = threading.Thread(target=printHello)
t2 = threading.Thread(target=printNihao)
t1.setDaemon(False)
t2.setDaemon(False)
t1.start()
t2.start()
print("main threading ended...")
方式2:继承threading.Thread,并重写run
import threading
import time
class CustomThread(threading.Thread):
def __init__(self, thread_name):
# step 1: call base __init__ function
super(CustomThread, self).__init__(name=thread_name)
self._tname = thread_name
def run(self):
# step 2: overide run function
time.sleep(0.5)
print("This is %s running...." % self._tname)
if __name__ == "__main__":
t1 = CustomThread("thread 1")
t2 = CustomThread("thread 2")
t1.setDaemon(False)
t2.setDaemon(False)
t1.start()
t2.start()
print("This is main function")
上面两种方法本质上都是直接或者间接使用threading.Thread类
下面是threading.Thread提供的线程对象方法和属性:
start():创建线程后通过start启动线程,等待CPU调度,为run函数执行做准备;
run():线程开始执行的入口函数,函数体中会调用用户编写的target函数,或者执行被重载的run函数;
join([timeout]):阻塞挂起调用该函数的线程,直到被调用线程执行完成或超时。通常会在主线程中调用该方法,等待其他线程执行完成。
name、getName()&setName():线程名称相关的操作;
ident:整数类型的线程标识符,线程开始执行前(调用start之前)为None;
isAlive()、is_alive():start函数执行之后到run函数执行完之前都为True;
daemon、isDaemon()&setDaemon():守护线程相关;