threading 多线程处理工具

单线程

1.案例

  1. from time import ctime,sleep
  2. def music():
  3. for i in range(2):
  4. print "I was listening to music. %s" %ctime()
  5. sleep(1)
  6. def move():
  7. for i in range(2):
  8. print "I was at the movies! %s" %ctime()
  9. sleep(5)
  10. if __name__ == '__main__':
  11. music()
  12. move()
  13. print "all over %s" %ctime()

多线程

1.案例

  1. import threading
  2. from time import ctime,sleep
  3. def music(func):
  4. for i in range(2):
  5. print "I was listening to %s. %s" %(func,ctime())
  6. sleep(1)
  7. def move(func):
  8. for i in range(2):
  9. print "I was at the %s! %s" %(func,ctime())
  10. sleep(5)
  11. #多线程配置
  12. t1 = threading.Thread(target=music,args=(u'GD',))
  13. t2 = threading.Thread(target=move,args=(u'阿凡达',))
  14. if __name__ == '__main__':
  15. #所有多线程一起启动
  16. #设置非守护进程,父进程会等待所有子进程执行完毕,父进程才会退出
  17. t1.setDaemon(False)
  18. t1.start()
  19. #设置守护进程 (子线程启动后,父进程不等待子进程继续执行,当父进程执行完毕,子进程也一起退出)
  20. t2.setDaemon(True)
  21. t2.start();
  22. print "all over %s" %ctime()
  23. #当前运行中的Thread对象列表
  24. for item in threading.enumerate():
  25. print item