做淘客网站能干嘛,昭通市住房和城乡建设局网站,wordpress 增加注册页面,如何做彩票网站信息一 概念介绍Thread 是threading模块中最重要的类之一#xff0c;可以使用它来创建线程。有两种方式来创建线程#xff1a;一种是通过继承Thread类#xff0c;重写它的run方法#xff1b;另一种是创建一个threading.Thread对象#xff0c;在它的初始化函数(__init__)中将可…一 概念介绍Thread 是threading模块中最重要的类之一可以使用它来创建线程。有两种方式来创建线程一种是通过继承Thread类重写它的run方法另一种是创建一个threading.Thread对象在它的初始化函数(__init__)中将可调用对象作为参数传入.Thread模块是比较底层的模块Threading模块是对Thread做了一些包装的可以更加方便的被使用。另外在工作时,有时需要让多条命令并发的执行, 而不是顺序执行.二 代码样例#!/usr/bin/python# encodingutf-8# Filename: thread-extends-class.py# 直接从Thread继承创建一个新的class把线程执行的代码放到这个新的 class里import threadingimport timeclass ThreadImpl(threading.Thread):def __init__(self, num):threading.Thread.__init__(self)self._num numdef run(self):global total, mutex# 打印线程名print threading.currentThread().getName()for x in xrange(0, int(self._num)):# 取得锁mutex.acquire()total total 1# 释放锁mutex.release()if __name__ __main__:#定义全局变量global total, mutextotal 0# 创建锁mutex threading.Lock()#定义线程池threads []# 创建线程对象for x in xrange(0, 40):threads.append(ThreadImpl(100))# 启动线程for t in threads:t.start()# 等待子线程结束for t in threads:t.join()# 打印执行结果print total#!/usr/bin/python# encodingutf-8# Filename: thread-function.py# 创建线程要执行的函数把这个函数传递进Thread对象里让它来执行import threadingimport timedef threadFunc(num):global total, mutex# 打印线程名print threading.currentThread().getName()for x in xrange(0, int(num)):# 取得锁mutex.acquire()total total 1# 释放锁mutex.release()def main(num):#定义全局变量global total, mutextotal 0# 创建锁mutex threading.Lock()#定义线程池threads []# 先创建线程对象for x in xrange(0, num):threads.append(threading.Thread(targetthreadFunc, args(100,)))# 启动所有线程for t in threads:t.start()# 主线程中等待所有子线程退出for t in threads:t.join()# 打印执行结果print totalif __name__ __main__:# 创建40个线程main(40)#!/usr/bin/python# encodingutf-8# Filename: put_files_hdfs.py# 让多条命令并发执行,如让多条scp,ftp,hdfs上传命令并发执行,提高程序运行效率import datetimeimport osimport threadingdef execCmd(cmd):try:print 命令%s开始运行%s % (cmd,datetime.datetime.now())os.system(cmd)print 命令%s结束运行%s % (cmd,datetime.datetime.now())except Exception, e:print %s\t 运行失败,失败原因\r\n%s % (cmd,e)if __name__ __main__:# 需要执行的命令列表cmds [ls /root,pwd,]#线程池threads []print 程序开始运行%s % datetime.datetime.now()for cmd in cmds:th threading.Thread(targetexecCmd, args(cmd,))th.start()threads.append(th)# 等待线程运行完毕for th in threads:th.join()print 程序结束运行%s % datetime.datetime.now()