python 多线程

本文是参考了廖雪峰老师的文章:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832360548a6491f20c62d427287739fcfa5d5be1f000

  Python的标准库提供了两个模块:threadthreadingthread是低级模块,threading是高级模块,对thread进行了封装。绝大多数情况下,我们只需要使用threading这个高级模块。

启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:

  import time
  import threading

  # 新线程执行的代码:
  def test_Threading():
    print 'thread %s is running...' % threading.current_thread().name
    n = 0
    while n < 5:
      n = n + 1
      print 'thread %s >>> %s' % (threading.current_thread().name, n)
      time.sleep(1)
    print 'thread %s ended.' % threading.current_thread().name

  print 'thread %s is running...' % threading.current_thread().name
  t = threading.Thread(target=test_Threading, name='LoopThread')
  t.start()
  t.join()
  print 'thread %s ended.' % threading.current_thread().name

 
 
原文地址:https://www.cnblogs.com/shaosks/p/5627113.html