本文實例講述了Python3多線程操作。分享給大家供大家參考,具體如下:
python3 線程中常用的兩個模塊為:
_thread
threading(推薦使用)
thread 模塊已被廢棄。用戶可以使用 threading 模塊代替。所以,在 python3 中不能再使用"thread" 模塊。為了兼容性,python3 將 thread 重命名為 "_thread"。
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# -*- 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程序設計有所幫助。
原文鏈接:https://blog.csdn.net/nuli888/article/details/51970863