理解Python THREADING模块中的JOIN()方法


    Join方法:如果一个线程在执行过程中要调用另外一个线程,并且等到其完成以后才能接着执行

那么在调用这个线程时可以使用被调用线程的join方法。

 

代码如下:

import threading
import time
from time import sleep


#第一种,创建函数并且传入Thread对象中
def now():
    return str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

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

def main():
    print 'starting at:',now()
    threadpool = []

    for i in xrange(10):
        th = threading.Thread(target=test, args=(i, 2))
        threadpool.append(th)

    for th in threadpool:
        th.start()

    for th in threadpool:
        threading.Thread.join(th)

    print 'all Done at:', now()

if __name__ == '__name__':
    main()

在程序中,最后join()方法的调用,是主线程挨个调用子线程的 join()方法。当所调用线程都执行完毕后,

主线程才会执行下面的代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值