Python使用Threading创建Thread实例

import threading
from time import sleep,ctime
'''Python使用Threading创建Thread实例'''
#不必使用线程锁
#使用这个方法可以实现同步线程

loops = [4,2]

def loop(nloop, nsec):
    print('start loop',nloop,'at: ',ctime())
    sleep(nsec)
    print('loop',nloop,'done at: ',ctime())

def main():
    print('starting at: ',ctime())
    threads = []                            #创建空列表来存放线程对象
    nloops = range(len(loops))  #loops列表的长度范围是2

    for i in nloops:            #实例化两个对象
        '''当实例化每个Thread对象时,传递target和args'''
        t = threading.Thread(target=loop, args=(i,loops[i]))    #创建线程,执行loop函数
        threads.append(t)       #将实例化线程对象的返回值添加到threads列表里面
    for i in nloops:
        threads[i].start()      #通过调用start方法执行线程
    for i in nloops:
        threads[i].join()       #等待上一个线程结束或者超时,调用join方法开始新的线程执行

    print('All Done at: ',ctime())

if __name__ == '__main__':

    main()

创建Thread实例,传给他一个可调用的类实例

import threading
from time import ctime,sleep

loops = [4,2]

class ThreadFunc(object):
    '''使用构造函数初始化这些属性'''
    def __init__(self,func,args,name = ''):
        self.name = name
        self.func = func
        self.args = args
    '''通过调用__call__(self)方法,创建新的线程'''
    def __call__(self):
        self.func(*self.args)    #调用这个方法可以传递参数

def loop(nloop , nsec):
    print('Starting loop',nloop,'at:',ctime())
    sleep(nsec)
    print('loop',nloop,'done at: ',ctime())

def main():
    print('starting at: ',ctime())
    threads = []
    nloops = range(len(loops))

    for i in nloops:
        '''创建所有的线程'''
        t = threading.Thread( target= ThreadFunc(loop, (i,loops[i]),loop.__name__))
        threads.append(t)
    '''开始所有的线程'''
    for i in nloops:
        threads[i].start()
    '''等待线程关闭'''
    for i in nloops:
        threads[i].join()

    print('All done at: ',ctime())

if __name__ == '__main__':
    main()


猜你喜欢

转载自blog.csdn.net/qq_37504771/article/details/80740255