Python3多线程操作简单示例

yipeiwu_com5年前Python基础

本文实例讲述了Python3多线程操作。分享给大家供大家参考,具体如下:

python3 线程中常用的两个模块为:

_thread

threading(推荐使用)

thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 python3 中不能再使用"thread" 模块。为了兼容性,python3 将 thread 重命名为 "_thread"。

test.py

# -*- coding:utf-8 -*-
#!/usr/bin/python3
import _thread
import time
# 定义线程调用函数
def echo_name(tag,delay):
  count=0
  while count<5:
    time.sleep(delay)
    count+=1
    print("%s:%s" % ( tag,time.ctime(time.time()) ))
#创建2个线程
try:
  _thread.start_new_thread( echo_name,("thread_1",2))
  _thread.start_new_thread( echo_name,("thread_2",5))
except:
  print("error:无法启动线程")
#死循环
while 1:
  pass

执行结果

[root@mail pythonCode]# python3 test.py
thread_1:Wed Jul 20 18:03:39 2016
thread_1:Wed Jul 20 18:03:41 2016
thread_2:Wed Jul 20 18:03:42 2016
thread_1:Wed Jul 20 18:03:43 2016
thread_1:Wed Jul 20 18:03:45 2016
thread_2:Wed Jul 20 18:03:47 2016
thread_1:Wed Jul 20 18:03:47 2016
thread_2:Wed Jul 20 18:03:52 2016
thread_2:Wed Jul 20 18:03:57 2016
thread_2:Wed Jul 20 18:04:02 2016

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

PyTorch学习:动态图和静态图的例子

动态图和静态图 目前神经网络框架分为静态图框架和动态图框架,PyTorch 和 TensorFlow、Caffe 等框架最大的区别就是他们拥有不同的计算图表现形式。 TensorFlow...

pandas 对日期类型数据的处理方法详解

pandas 对日期类型数据的处理方法详解

pandas 的日期/时间类型有如下几种: Concept Scalar Class Array Class panda...

django 捕获异常和日志系统过程详解

这一块的内容很少, 异常使用try except即可, 日志只需要几行配置. 使用装饰器捕获方法内的所有异常 我使用装饰器来整个包裹一个方法, 捕获方法中的所有异常信息.并将其转为j...

Python实现滑动平均(Moving Average)的例子

Python中滑动平均算法(Moving Average)方案: #!/usr/bin/env python # -*- coding: utf-8 -*- import nump...

python-str,list,set间的转换实例

实例如下: a = '123abbcc!@#' b = ['1', '2', '3', 'a', 'b', 'c', '!', '@', '#'] c = set(['a', '!...