鱼C论坛

 找回密码
 立即注册
查看: 2505|回复: 1

多线程的一点疑惑

[复制链接]
发表于 2015-7-2 10:47:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
代码如下:
  1. #!/usr/bin/env python
  2. import threading
  3. import time


  4. class MyThread(threading.Thread):
  5.     def __init__(self,event):
  6.         threading.Thread.__init__(self)
  7.         self.event = event

  8.     def run(self):
  9.         if not self.event.isSet():
  10.             print '{0} is sleep...'.format(self.getName())
  11.             self.event.wait()
  12.             print '{0} is awaked!'.format(self.getName())

  13. event = threading.Event()
  14. event.clear()

  15. thlist = []

  16. for i in range(1,5):
  17.     i = MyThread(event)
  18.     thlist.append(i)

  19. for i in thlist:
  20. #    i.setDaemon(True)
  21.     i.start()
  22. print 'Sleep 1 second..'
  23. time.sleep(1)
  24. event.set()
复制代码


执行结果如下:

  1. root@localhost:~# python --version
  2. Python 2.7.3
  3. root@localhost:~# python test.py
  4. Thread-1 is sleep...
  5. Thread-2 is sleep...
  6. Thread-3 is sleep...
  7. Sleep 1 second..
  8. Thread-4 is sleep...
  9. Thread-1 is awaked!
  10. Thread-2 is awaked!
  11. Thread-3 is awaked!
  12. Thread-4 is awaked!
复制代码


最后一个线程为什么比主线程后执行呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2015-7-2 11:04:07 | 显示全部楼层
本帖最后由 赢在未来° 于 2015-7-2 11:05 编辑

以下为猜测,不知道对不对~~~
大致有点懂了,因为每个线程的创建都需要开销,创建最后一个线程会花费一些开销,而这时主线程已经执行完了
代码可以这样改一下:
  1. #!/usr/bin/env python
  2. import threading
  3. import time


  4. class MyThread(threading.Thread):
  5.     def __init__(self,event):
  6.         threading.Thread.__init__(self)
  7.         self.event = event

  8.     def run(self):
  9.         if not self.event.isSet():
  10.             self.event.wait()
  11.             print '{0} is awaked!'.format(self.getName())

  12. event = threading.Event()
  13. event.clear()

  14. thlist = []

  15. for i in range(1,5):
  16.     i = MyThread(event)
  17.     thlist.append(i)

  18. for i in thlist:
  19. #    i.setDaemon(True)
  20.     print '{0} is start...'.format(i)
  21.     i.start()

  22. print 'Sleep 1 second..'
  23. time.sleep(1)

  24. event.set()
复制代码

  1. root@localhost:~# python test.py
  2. <MyThread(Thread-1, initial)> is start...
  3. <MyThread(Thread-2, initial)> is start...
  4. <MyThread(Thread-3, initial)> is start...
  5. <MyThread(Thread-4, initial)> is start...
  6. Sleep 1 second..
  7. Thread-1 is awaked!
  8. Thread-2 is awaked!
  9. Thread-3 is awaked!
  10. Thread-4 is awaked!
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-16 17:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表