1、分为主线程和子线程

2、设置守护线程setDaemon()

3、在子线程运行结束之前,主线程无法执行,子线程结束,主线程才执行join()

 

备注:通过多程线的方式运行脚本,总的时间没变化

 

代码:

#coding=utf-8
import threading
from time import ctime,sleep


def music(func):
    for i in range(2):
        print "I was listening to %s. %s" %(func,ctime())
        sleep(1)

def move(func):
    for i in range(2):
        print "I was at the %s! %s" %(func,ctime())
        sleep(5)

threads = []
t1 = threading.Thread(target=music,args=(u'吃饭',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'喝汤',))
threads.append(t2)

if __name__ == '__main__':
    for t in threads:
        t.setDaemon(True)
        t.start()
        t.join()
    print "all over %s" %ctime()

修正版

当t2线程结束之后,程序结束,但是t1进程还没有执行完毕,这明显与我们的初衷不符。所以建议改成

if __name__ == '__main__':

    for t in threads:

        t.start()

    for t in threads:

        t.join()

 print "all over %s" %ctime()

转至:https://www.cnblogs.com/fnng/p/3670789.htmlhttps://www.cnblogs.com/fnng/p/3670789.html

相关文章:

  • 2022-03-01
  • 2021-06-10
  • 2021-06-29
  • 2021-09-29
  • 2022-01-13
  • 2022-12-23
  • 2022-03-08
  • 2022-12-23
猜你喜欢
  • 2022-01-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-07
  • 2021-04-02
  • 2021-08-17
  • 2021-07-25
相关资源
相似解决方案