多线程与线程数控制

 1 #!/usr/bin/python 
 2 #coding:utf-8 
 3 import threading 
 4 import datetime 
 5 import logging 
 6 import time
 7 import random
 8 
 9 logging.basicConfig(level = logging.DEBUG,format='(%(threadName)-10s) %(message)s',) 
10 list = ['192.168.0.0', '192.168.0.1', '192.168.0.2', '192.168.0.3', '192.168.0.4', '192.168.0.5', '192.168.0.6', '192.168.0.7', '192.168.0.8', '192.168.0.9',
11  '192.168.0.10', '192.168.0.11', '192.168.0.12', '192.168.0.13', '192.168.0.14', '192.168.0.15', '192.168.0.16', '192.168.0.17', '192.168.0.18']
12 class Test(threading.Thread): 
13     def __init__(self,threadingSum, ip): 
14         threading.Thread.__init__(self) 
15         self.ip = ip 
16         self.threadingSum = threadingSum 
17                                                               
18     def run(self): 
19         with self.threadingSum: 
20             logging.debug("%s start!" % self.ip) 
21             time.sleep(random.randint(1,3)) 
22             logging.debug('%s Done!' % self.ip) 
23                                                                   
24                                                               
25 if __name__ == "__main__": 
26     #设置线程数 
27     threadingSum = threading.Semaphore(3) 
28                                                           
29     #启动线程 
30     for ip in list: 
31         t = Test(threadingSum,ip) 
32         t.start() 
33     #等待所有线程结束 
34     for t in threading.enumerate(): 
35         if t is threading.currentThread(): 
36             continue
37         t.join() 
38                                                               
39     logging.debug('Done!')

 

posted @ 2014-03-20 15:22  r3call  阅读(794)  评论(0编辑  收藏  举报