python之通过thread来实现多进程

本文展示了一个Python中使用多线程的示例代码,通过创建两个子线程并使用join方法来确保主线程等待子线程完成。这有助于理解线程在Python中的基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:
import threading, time

class Test1(threading.Thread):
  def __init__(self, name):
    super().__init__(name=name)

  def run(self):
    print('test1 start')
    time.sleep(2)
    print('test1 end')


class Test2(threading.Thread):
  def __init__(self, name):
    super().__init__(name=name)

  # 继承thread必须覆盖的方法
  def run(self):   
    print('test2 start')
    time.sleep(4)
    print('test2 end')


if __name__ == '__main__':
  thread1 = Test1('test1')
  thread2 = Test2('test2')
  start_time = time.time()
  thread1.start()   
  thread2.start()

  # 使用join方法,这两个线程就会阻塞主线程的运行,print('main')就会后执行
  thread1.join()   
  thread2.join()
  print('main')
结果:

1347866-20181227223338350-1421117161.png

转载于:https://www.cnblogs.com/raind/p/10187930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值