python3 多线程的实现

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(): 设置线程名。

参考文献:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值