@Dukebf
2017-07-11T16:14:25.000000Z
字数 1876
阅读 1466
python 多线程
Thread是threading模块中重要的类.创建线程可以有两种方法:
使用继承来使用多线程,可以对线程进行更多的自定义.如线程锁,线程等待,定义线程名字等等.
线程一般可以和队列Queue进行搭配.
输出打印IP
#!/usr/bin/python#-*-coding:utf-8-*-import threadingfrom queue import Queueclass Thread_ip(threading.Thread):def __init__(self,thread_name,queue):super(Thread_ip,self).__init__(name=thread_name)# 使用super显示调用父类# 也可以使用下面的方法,显示调用# threading.Thread().__init__(self,name=thread_name)# thread_stop: (可选)指定线程是否停止self.name = thread_nameself.thread_stop = Falseself.__queue = queuedef run(self):""" (必须重写)重写父类run方法,线程启动后执行该方法"""while not self.__queue.empty():print(self.__queue.get(),'name:{}'.format(self.name))def stop(self):""" (可选)重写父类stop方法,调用时线程停止"""self.thread_stop = Trueif __name__ == '__main__':Q = Queue()for i in range(255):Q.put('180.149.132.%s' % i)max_thread = 5 # 定义最大线程数量threads = []while not Q.empty():# 队列还没有空if len(threads) < max_thread and not Q.empty():# 还可以增加线程,启用新线程thread = Thread_ip(queue=Q,thread_name='thread-'+str(max_thread-len(threads)))thread.start() # 启动线程threads.append(thread)for thread in threads:if not thread.is_alive():# 停止已经不活动的线程# 并从当前的线程列表中移出thread.stop()threads.remove(thread)if Q.empty():# 如果队列已经空了,则将当前正在执行的线程退出for thread in threads:thread.join()print('continue')print('end')
线程在执行的各个过程,可以自行打印看看效果.
除了用while循环控制线程,还可以简单的用for循环控制线程数.
将上面的while循环修改:
# 设定最大线程数max_thread = 5threads = []for i in range(max_thread):# 初始化线程thread = Thread_ip(queue=Q,thread_name='thread-'+str(i))threads.append(thread)# 启动线程,并将让主线程阻塞for thread in threads:thread.start()for thread in threads:thread.join()print('end')
对象的使用就相对比较简单
import threadingimport timedef print_ip(ip):time.sleep(1)print('ip: {}'.format(ip))for i in range(5):ip = '192.168.0.%s' % it = threading.Thread(target=print_ip,args=(ip,))t.start()print('end')
上面的例子中,只是简单的创建了线程
此外,也还可以用队列Queue来传输数据
join()方法可以可以阻塞主进程.达到让所有线程都结束了,主进程才退出的效果.