This is thread T1
0
1
2
T1 is over
main thread is over
阻塞等待 thread1 结束,才执行下面语句
主线程等待
if __name__ == '__main__':
thread1 = Th("T1 ")
thread1.setDaemon(True)
#要在线程执行之前就设置这个量
thread1.start()
print "main thread is over"
报错: Exception in thread T1 (most likely raised during interpreter shutdown):
也就是主线程不等待子线程就结束了。
多个子线程
if __name__ == '__main__':
for i in range(3):
t = Th(str(i))
t.start()
print "main thread is over"
这里的 t 可同时处理多个线程,即 t 为线程句柄,重新赋值不影响线程。
这里奇怪的是,运行 t.run() 时,不会再执行其他线程。虽不明,还是用 start() 吧。暂且理解为 start() 是非阻塞并行的,而 run 是阻塞的。
线程锁
threading 提供线程锁,可以实现线程同步。
import threading
import time
class Th(threading.Thread):
def __init__(self, thread_name):
threading.Thread.__init__(self)
self.setName(thread_name)
def run(self):
threadLock.acquire()
#获得锁之后再运行
print "This is thread " + self.getName()
for i in range(3):
time.sleep(1)
print str(i)
print self.getName() + " is over"
threadLock.release()
#释放锁
if __name__ == '__main__':
threadLock = threading.Lock()
#设置全局锁
thread1 = Th('Thread_1')
thread2 = Th('Thread_2')
thread1.start()
thread2.start()
得到结果:
This is thread Thread_1
0
1
2
Thread_1 is over
This is thread Thread_2
0
1
2
Thread_2 is over










