🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ### threading.Thread类 Thread是对thread模块的封装,开启的子线程默认是非守护线程,不会随主线程一切结束。 #### 常用方法 ``` start() #开始执行该线程 join(timeout=None) #子线程join到主线程 setName(name) --> thread.name getName() #取得线程名 is_alive()/isAlive() #线程是否存活的标志 setDaemon(False) --> thread.daemon = False isDaemon() activeCount()/active_count() # 当前活动对象个数 currentThread()/current_thread() # 返回当前Thread对象 enumerate() # 返回Thread对象列表 ``` #### threading.Thread的初始化函数 ``` def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): ``` ![](http://i2.muimg.com/567571/06fdf903d612fc8a.png) ### 直接调用线程 `join`命名来源于posix标准。子线程join到主线程(启动程序的线程,比如c语言执行main函数的线程)。你的问题可能在于没有理解join,阻塞线程仅仅是一个表现,而非目的。其目的是等待当前线程执行完毕后,”计算单元”与主线程汇合。 ``` #!/usr/bin/env python # coding: utf-8 import threading from time import ctime,sleep def music(func): for i in range(5): print "I was listening to %s. %s" %(func,ctime()) sleep(1) def move(func): for i in range(1): print "I was at the %s! %s" %(func,ctime()) sleep(2) threads = [] t1 = threading.Thread(target=music, args=(u'爱情买卖',)) threads.append(t1) t2 = threading.Thread(target=move, args=(u'阿凡达',)) threads.append(t2) if __name__ == '__main__': for t in threads: t.setDaemon(False) t.start() # 等待线程结束,与主线程会和,这两个线程都阻塞,主线程不会往下执行。 for t in threads: t.join() print "all over %s" %ctime() ``` ### 自定义线程类 ``` #!/usr/bin/python # coding: UTF-8 import threading import time class myThread(threading.Thread): #继承父类threading.Thread def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 print "Starting " + self.name printTime(self.name, self.counter) print "Exiting " + self.name def printTime(threadName, counter): for i in xrange(counter): time.sleep(1) print "%s: %s" % (threadName, time.ctime(time.time())) # 创建新线程 thread1 = myThread(1, "Thread-1", 3) thread2 = myThread(2, "Thread-2", 5) # 开启线程 thread1.start() thread2.start() print "Exiting Main Thread" ``` #### 线程池 使用信号量充当线程池 下面的做法同样会造成资源竞争,应该将信号量参数改为1 ``` #!/usr/bin/env python # coding: utf-8 import time from threading import Thread, Lock, BoundedSemaphore num = 0 def add(): time.sleep(1) with lock: global num num += 1 print num lock = BoundedSemaphore(1000) for i in range(10000): add_thread = Thread(target=add, args=()) add_thread.start() ```