python中多线程的简单案例

#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(4)

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:
        # 将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。
        t.setDaemon(True)
        t.start()

    # 等待for循环里的两个进程都结束后,才去执行主进程
    for t in threads:
        t.join()

    print "all over %s" %ctime()

猜你喜欢

转载自blog.csdn.net/t8116189520/article/details/80015854