threading多线程,join方法,setDeamon,for循环作用域

 1 import threading
 2 import time
 3 def hi(x):
 4     print('内容是%s'%x,time.ctime())
 5     time.sleep(3)
 6     print('t1结束',time.ctime())
 7 def hey(x):
 8     print('内容是%s'%x,time.ctime())
 9     time.sleep(5)
10     print('t2结束',time.ctime())
11 
12 if __name__ == '__main__':
13     t1 = threading.Thread(target=hi,args=('x',))
14     t2 = threading.Thread(target=hey,args=('y',))
15 
16     t1.start()
17     t2.start()
18 
19     print('ending')
20 
21 
22 
23 import threading
24 import time
25 def hi(x):
26     print('内容是%s'%x,time.ctime())
27     time.sleep(3)
28     print('t1结束',time.ctime())
29 def hey(x):
30     print('内容是%s'%x,time.ctime())
31     time.sleep(5)
32     print('t2结束',time.ctime())
33 
34 if __name__ == '__main__':
35     t1 = threading.Thread(target=hi,args=('x',))        #target方法名
36     t2 = threading.Thread(target=hey,args=('y',))       #args要传的参数
37 
38     t1.start()          #t1程序开始
39     t2.start()          #t2开始执行
40 
41     t1.join()           #t1执行完后再向后执行
42     t2.join()           #t2执行完后再向后执行
43 
44     print('ending')

 上join

下setDeamon

 1 import threading
 2 import time
 3 def hi(x):
 4     print('内容是%s'%x,time.ctime())
 5     time.sleep(3)
 6     print('t1结束',time.ctime())
 7 def hey(x):
 8     print('内容是%s'%x,time.ctime())
 9     time.sleep(5)
10     print('t2结束',time.ctime())
11 
12 if __name__ == '__main__':
13     t1 = threading.Thread(target=hi,args=('x',))        #target方法名
14     t2 = threading.Thread(target=hey,args=('y',))       #args要传的参数
15 
16     # t1.setDaemon(True)  #setDaemon(True)表示运行时线程跟随主程序一起结束
17     t2.setDaemon(True)
18 
19     t1.start()          #t1程序开始
20     t2.start()          #t2开始执行
21 
22     print('ending')

其他方法

 1 # run():  线程被cpu调度后自动执行线程对象的run方法
 2 # start():启动线程活动。
 3 # isAlive(): 返回线程是否活动的。
 4 # getName(): 返回线程名。
 5 # setName(): 设置线程名。
   # 上面是threading实例化的对象的方法
 7 threading模块提供的一些方法:
 8 # threading.currentThread(): 返回当前的线程变量。
 9 # threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
10 # threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

 

 关于for循环作用域

1 l = ['a','b']
2 for i in l:
3     print(i)
4 print('-------------')
5 print(i)        #if else for 没说作用域的问题    这个时候调用i输出的是最后一次循环的结果

 

posted on 2018-06-25 00:00  胡慢  阅读(122)  评论(0)    收藏  举报

导航