首页 > 编程 > Python > 正文

Python 多线程2

2019-11-06 06:30:19
字体:
来源:转载
供稿:网友

守护进程

import threadingfrom time import ctime,sleepdef music(func): for i in range(2): PRint "I --> %s. %s" %(func,ctime()) sleep(1)def movie(func): for i in range(2): print "I --> %s! %s" %(func,ctime()) sleep(5)threads = []t1 = threading.Thread(target=music,args=(u'Music',))threads.append(t1)t2 = threading.Thread(target=movie,args=(u'Movie',))threads.append(t2)if __name__ == '__main__': for t in threads: t.setDaemon(True) t.start() print "MainThread is over %s!" %ctime()

I –> Music. Mon Mar 06 18:43:39 2017 I –> Movie! Mon Mar 06 18:43:39 2017 MainThread is over Mon Mar 06 18:43:39 2017! I –> Music. Mon Mar 06 18:43:40 2017 I –> Movie! Mon Mar 06 18:43:44 2017

setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线 程也继续执行下去,当父线程执行完最后一条语句print “all over %s” %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。

创建进程

import threadingfrom time import ctime,sleepdef music(func): for i in range(2): print 'I --> %s! %s' %(func,ctime()) sleep(1)def movie(func): for i in range(2): print 'I --> %s! %s'%(func,ctime()) sleep(5)threads = []t1 = threading.Thread(target = music,args =(u'Music',))threads.append(t1)t2 = threading.Thread(target = movie,args =(u'Movie',))threads.append(t2)if __name__=='__main__': for t in threads: t.setDaemon(True) t.start() t.join() print 'MainThread is over! %s' %ctime()

输出结果:

I –> Music! Mon Mar 06 19:02:27 2017 I –> Movie! Mon Mar 06 19:02:27 2017 I –> Music! Mon Mar 06 19:02:28 2017 I –> Movie! Mon Mar 06 19:02:32 2017 MainThread is over! Mon Mar 06 19:02:37 2017

我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表