码迷,mamicode.com
首页 > 编程语言 > 详细

day35 python多线程

时间:2017-07-18 01:48:55      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:threading   logs   from   python   read   range   coding   time   启动   

Python多线程

 

 

多线程-threading

pythonthread模块是?较底层的模块, pythonthreading
模块是对thread做了?些包装的, 可以更加?便的被使?
1. 使?threading模块

单线程执? 

1 import time
2 def saySorry():
3     print("亲爱的, 我错了, 我能吃饭了吗? ")
4     time.sleep(1)
5 if __name__ == "__main__":
6     for i in range(5):
7         saySorry()

运?结果: 打印了五次花了五秒

亲爱的, 我错了, 我能吃饭了吗? 
亲爱的, 我错了, 我能吃饭了吗? 
亲爱的, 我错了, 我能吃饭了吗? 
亲爱的, 我错了, 我能吃饭了吗? 
亲爱的, 我错了, 我能吃饭了吗? 

Process finished with exit code 0

  

多线程执? :一起打印,花了一秒

 1 #coding=utf-8
 2 import threading
 3 import time
 4 def saySorry():
 5     print("亲爱的, 我错了, 我能吃饭了吗? ")
 6     time.sleep(1)
 7 
 8 if __name__ == "__main__":
 9     for i in range(5):
10         t = threading.Thread(target=saySorry)
11         t.start() #启动线程, 即让线程开始执?

 

说明

1. 可以明显看出使?了多线程并发的操作, 花费时间要短很多
2. 创建好的线程, 需要调? start() ?法来启动

2. 主线程会等待所有的?线程结束后才结束

 

 

 1 #coding=utf-8
 2 import threading
 3 from time import sleep,ctime
 4 
 5 
 6 def sing():
 7     for i in range(3):
 8         print("正在唱歌...%d"%i)
 9         sleep(1)
10 
11 
12 def dance():
13     for i in range(3):
14         print("正在跳舞...%d"%i)
15         sleep(1)
16 
17 
18 if __name__ == __main__:
19     print(---开始---:%s%ctime())
20     t1 = threading.Thread(target=sing)
21     t2 = threading.Thread(target=dance)
22     t1.start()
23     t2.start()
24     #sleep(5) # 屏蔽此?代码, 试试看, 程序是否会??结束?
25     print(---结束---:%s%ctime())

 

3. 查看线程数量

 

 1 #coding=utf-8
 2 import threading
 3 from time import sleep,ctime
 4 
 5 
 6 def sing():
 7     for i in range(3):
 8         print("正在唱歌...%d"%i)
 9         sleep(1)
10 
11 
12 def dance():
13     for i in range(3):
14         print("正在跳舞...%d"%i)
15         sleep(1)
16 
17 
18 if __name__ == __main__:
19     print(---开始---:%s%ctime())
20     t1 = threading.Thread(target=sing)
21     t2 = threading.Thread(target=dance)
22     t1.start()
23     t2.start()
24 
25     while True:
26         length = len(threading.enumerate())
27         print(当前运?的线程数为: %d%length)
28         if length<=1:
29             break
30     sleep(0.5)

 

day35 python多线程

标签:threading   logs   from   python   read   range   coding   time   启动   

原文地址:http://www.cnblogs.com/alwaysInMe/p/7197977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!