#!/usr/bin/pythonn # -*- coding: UTF-8 -*- """ 学习线程 thread 总结: 1. 主线程退出,所有子线程都退出 2. 子线程 能直接读取外部变量 3. thread.start_new_thread 调用后,立即执行并发代码了,不像有些模块,执行完后,要调用start方法才执行并发代码,xxxx.yyyy().start() 使用: 调用 thread.start_new_thread( <func>,(parmas,parmas)) 根据上述 第一条 原则,看情况是否在 启动 线程后 ,主线程代码如何处理 """ import thread import time import threading a = 0 # 不同线程共同操作数据 def print_time(threadname,delay): global a print "thread %s,%s start" % (threading.currentThread().getName(),threadname) count = 0 while count <3: time.sleep(delay) count +=1 a +=1 print "%d,%s,%s:%s" % (a,threading.currentThread().getName(),threadname,time.ctime(time.time()) ) print "thread %s,%s end" % (threading.currentThread().getName(),threadname) print "main:%s start" % threading.currentThread().getName() try: thread.start_new_thread(print_time,("thread1",2,)) thread.start_new_thread(print_time,("thread2",3,)) except: print "Error: unable to start thread" pass time.sleep(7) print "main:%s end" % threading.currentThread().getName()
输出:
主线程等所有子线程跑完 time.sleep(15) Out: main:MainThread start thread Dummy-1,thread1 start thread Dummy-2,thread2 start 1,Dummy-1,thread1:Sat Sep 08 02:23:04 2018 2,Dummy-2,thread2:Sat Sep 08 02:23:05 2018 3,Dummy-1,thread1:Sat Sep 08 02:23:06 2018 4,Dummy-2,thread2:Sat Sep 08 02:23:08 2018 5,Dummy-1,thread1:Sat Sep 08 02:23:08 2018 thread Dummy-1,thread1 end 6,Dummy-2,thread2:Sat Sep 08 02:23:11 2018 thread Dummy-2,thread2 end main:MainThread end --------------------------------------------------- 主线程没有等子线程跑完 ,自己先跑完 time.sleep(7) Out: main:MainThread start thread Dummy-1,thread1 start thread Dummy-2,thread2 start 1,Dummy-1,thread1:Sat Sep 08 02:25:29 2018 2,Dummy-2,thread2:Sat Sep 08 02:25:30 2018 3,Dummy-1,thread1:Sat Sep 08 02:25:31 2018 4,Dummy-1,thread1:Sat Sep 08 02:25:33 2018 thread Dummy-1,thread1 end 5,Dummy-2,thread2:Sat Sep 08 02:25:33 2018 main:MainThread end