多线程threading模块的join()方法

join()方法

阻塞当前进程/线程,直到调用join方法的那个进程执行完,再继续执行当前进程。

join方法在java中即守护线程的概念:如果用户线程已经全部退出运行了,只剩下守护线程存在了,虚拟机也就退出了。 因为没有了被守护者,守护线程也就没有工作可做了,也就没有继续运行程序的必要了。

下面举例说明join()方法的作用。

  • eg1: 无join方法
import threading
from time import sleep, ctime

def world():

    for i in range(2):
        print "Hello World! " + ctime()
        sleep(2)

def ivanli():

    for i in range(2):
        print "Hello Ivanli! " + ctime()
        sleep(5)


def getThreads():

    threads = []
    t1 = threading.Thread(target=world)
    t2 = threading.Thread(target=ivanli)
    threads.append(t1)
    threads.append(t2)

    return threads

if __name__ == "__main__":

    threads = getThreads()
    for t in threads:
        t.start()

    print "main process .. "

输出:

Hello World! Wed Mar 21 21:40:32 2018
Hello Ivanli! Wed Mar 21 21:40:32 2018
main process .. 
Hello World! Wed Mar 21 21:40:34 2018
Hello Ivanli! Wed Mar 21 21:40:37 2018

Process finished with exit code 0

解释:
可见,无join方法,当线程t1和t2启动后,程序会将资源返回给主进程,主进程继续往下执行,所以执行了print,接着线程的sleep后,又再次循环一次执行了线程程序。

  • eg2: 有join方法,先start所有的线程,在join所有的线程
import threading
from time import sleep, ctime

def world():

    for i in range(2):
        print "Hello World! " + ctime()
        sleep(2)

def ivanli():

    for i in range(2):
        print "Hello Ivanli! " + ctime()
        sleep(5)


def getThreads():

    threads = []
    t1 = threading.Thread(target=world)
    t2 = threading.Thread(target=ivanli)
    threads.append(t1)
    threads.append(t2)

    return threads

if __name__ == "__main__":

    threads = getThreads()
    
    for t in threads:
        t.start()
        
    for t in threads:
        t.join()

    print "main process .. "

输出:

Hello World! Wed Mar 21 21:44:38 2018
Hello Ivanli! Wed Mar 21 21:44:38 2018
Hello World! Wed Mar 21 21:44:40 2018
Hello Ivanli! Wed Mar 21 21:44:43 2018
main process ..

解释:
可见,start所有的线程后,t1,t2同时启动,接着join所有的线程,阻塞当前进程,控制权不交给主进程,仍然在线程中,等所有线程都执行完毕后,再交给主进程,执行主进程的程序print

  • eg3: 有join方法,start1个线程,紧接着join该线程,再start另一个线程,再join另一个线程
import threading
from time import sleep, ctime

def world():

    for i in range(2):
        print "Hello World! " + ctime()
        sleep(2)

def ivanli():

    for i in range(2):
        print "Hello Ivanli! " + ctime()
        sleep(5)


def getThreads():

    threads = []
    t1 = threading.Thread(target=world)
    t2 = threading.Thread(target=ivanli)
    threads.append(t1)
    threads.append(t2)

    return threads

if __name__ == "__main__":

    threads = getThreads()

    for t in threads:
        t.start()
        t.join()

    print "main process .. "

输出:

Hello World! Wed Mar 21 21:46:23 2018
Hello World! Wed Mar 21 21:46:25 2018
Hello Ivanli! Wed Mar 21 21:46:27 2018
Hello Ivanli! Wed Mar 21 21:46:32 2018
main process .. 

解释:
可见,start t1线程后,紧接着就join守护t1线程,所有控制权在t1线程手上,只到t1线程结束,再start t2线程。

你可能感兴趣的:(多线程threading模块的join()方法)