python基础语法24-多线程实操

上一节说了多线程的理论知识,今天来实际操作一下。

1.创建线程
python中有2中方法创建线程,分别为函数和类继承
(1).使用函数来创建线程
调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下:
_thread.start_new_thread ( function, args[, kwargs] )
参数说明:
function - 线程函数。
args - 传递给线程函数的参数,他必须是个tuple类型。
kwargs - 可选参数。
示例:
import _thread
import time
#为线程定义一个函数
def demo(name, t):
   count = 0
   while count < 5:
      time.sleep(t)
      count += 1
      print ("%s: %s" % (name, time.ctime(time.time()) ))
#创建两个线程
try:
   _thread.start_new_thread( demo, ("线程-1", 2, ) )
   _thread.start_new_thread( demo, ("线程-2", 4, ) )
except:
   print ("无法启动线程")
while 1:
   pass
 结果如图:

(2).使用类继承来创建线程
直接从 threading.Thread继承创建一个新的子类&#x

猜你喜欢

转载自blog.csdn.net/a316495442/article/details/128457380
今日推荐