python3 线程_Python3多线程操作简单示例

本文实例讲述了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程序设计有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值