Python3 多线程为什么有的线程不会运行。

Python3 多线程为什么有的线程不会运行。,第1张

import _thread
import time

# 为线程定义一个函数
def print_time( threadName, delay):
   count = 0
   while count < 50:

      count += 1
      print ("%s: %s" % ( threadName, time.ctime(time.time()) ))

# 创建两个线程
try:
   _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print ("Error: 无法启动线程")

while 1:
   pass

##(代码示例来自菜鸟教程)

代码运行部分结果如下:

 如图所示。代码可能会只有一个线程运行,此时只需添加sleep函数即可,延时时间可按自己需求即可。(但是我在pyqt5 gui编程时sleep至少需要0.3才可以不卡死,读者可自行实验)

import _thread
import time

# 为线程定义一个函数
def print_time( threadName, delay):
   count = 0
   while count < 50:
      time.sleep(delay)  ####延时一定时间
      count += 1
      print ("%s: %s" % ( threadName, time.ctime(time.time()) ))

# 创建两个线程
try:
   _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print ("Error: 无法启动线程")

while 1:
   pass
#(示例代码来自菜鸟教程)

 部分结果如下:线程同时进行。

 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/737107.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-28
下一篇2022-04-28

发表评论

登录后才能评论

评论列表(0条)

    保存