Python3多线程操作简单示例

yipeiwu_com6年前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程序设计有所帮助。

相关文章

python中pygame针对游戏窗口的显示方法实例分析(附源码)

python中pygame针对游戏窗口的显示方法实例分析(附源码)

本文实例讲述了python中pygame针对游戏窗口的显示方法。分享给大家供大家参考,具体如下: 在这篇教程中,我将给出一个demo演示: 当我们按下键盘的‘f'键的时候,演示的窗口会切...

python用for循环求和的方法总结

Python中可以使用for循环实现累加求和 for循环语法: for 变量 in range(x): 循环需要执行的代码 如下实现1到n求和: def main():...

python发送伪造的arp请求

复制代码 代码如下:#!/usr/bin/env pythonimport socket s = socket.socket(socket.AF_PACKET, socket.SOCK_...

Python基础之getpass模块详细介绍

Python基础之getpass模块详细介绍

本文主要给大家介绍了关于Python中getpass模块的相关内容,分享出来供大家参考学习,话不多说了,来一起看看详细的介绍: getpass模块提供了平台无关的在命令行下输入密码的方法...

pip install urllib2不能安装的解决方法

python35 urllib2 不能用 Could not find a version that satisfies the requirement urllib2 (from...