1. _thread方法
_thread 提供了低级别的、原始的线程以及一个简单的锁
import _thread
import time
# 定义线程函数1
def print_test1():
while 1:
print("我是子线程1")
time.sleep(1)
def print_test2(argsValue):
while 1:
print(argsValue)
time.sleep(1)
try:
_thread.start_new_thread(print_test1,())
_thread.start_new_thread(print_test2,("我是子线程2",))
except:
print("ERROR!")
while 1:
print("我是主线程")
time.sleep(1)
2. threading模块法
threading 模块除了包含 _thread 模块中的所有方法,此外还包括:
threading.currentThread()
: 返回当前的线程变量。threading.enumerate()
: 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。threading.activeCount()
: 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:
run()
: 用以表示线程活动的方法。start()
:启动线程活动。join([time])
: 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。isAlive()
: 返回线程是否活动的。getName()
: 返回线程名。setName()
: 设置线程名。
参考文献: