python 多线程就这么简单

Bill78 85 0 0

（好吧！我们不纠结在DOS时代是否有听音乐和看影的应用。^_^）

from time import ctime,sleep def music(): for i in range(2): print "I was listening to music. %s" %ctime()
sleep(1) def move(): for i in range(2): print "I was at the movies! %s" %ctime()
sleep(5) if \_\_name\_\_ == '\_\_main\_\_':
music()
move() print "all over %s" %ctime()

我们先听了一首音乐，通过for循环来控制音乐的播放了两次，每首音乐播放需要1秒钟，sleep()来控制音乐播放的时长。接着我们又看了一场电影，

print "all over %s" %ctime()

\>>=========================== RESTART ================================
>>> I was listening to music. Thu Apr 17 10:47:08 2014 I was listening to music. Thu Apr 17 10:47:09 2014 I was at the movies! Thu Apr 17 10:47:10 2014 I was at the movies! Thu Apr 17 10:47:15 2014 all over Thu Apr 17 10:47:20 2014

#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) if \_\_name\_\_ == '\_\_main\_\_':
music(u'爱情买卖')
move(u'阿凡达') print "all over %s" %ctime()

\>>> ======================== RESTART ================================
>>> I was listening to 爱情买卖. Thu Apr 17 11:48:59 2014 I was listening to 爱情买卖. Thu Apr 17 11:49:00 2014 I was at the 阿凡达! Thu Apr 17 11:49:01 2014 I was at the 阿凡达! Thu Apr 17 11:49:06 2014 all over Thu Apr 17 11:49:11 2014

#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 \= 
threads.append(t2) if \_\_name\_\_ == '\_\_main\_\_': for t in threads:
t.setDaemon(True)
t.start() print "all over %s" %ctime()

for t in threads:

t.setDaemon(True)

t.start()

setDaemon()

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

start()

\>>> ========================= RESTART ================================
>>> I was listening to 爱情买卖. Thu Apr 17 12:51:45 2014 I was at the 阿凡达! Thu Apr 17 12:51:45 2014  all over Thu Apr 17 12:51:45 2014

从执行结果来看，子线程（muisc 、move ）和主线程（print "all over %s" %ctime()）都是同一时间启动，但由于主线程执行完结束，所以导致子线程也终止。

... if \_\_name\_\_ == '\_\_main\_\_': for t in threads:
t.setDaemon(True)
t.start() for t in threads:
t.join() print "all over %s" %ctime()

\>>> ========================= RESTART ================================
>>> I was listening to 爱情买卖. Thu Apr 17 13:04:11 2014  I was at the 阿凡达! Thu Apr 17 13:04:11 2014 I was listening to 爱情买卖. Thu Apr 17 13:04:12 2014 I was at the 阿凡达! Thu Apr 17 13:04:16 2014 all over Thu Apr 17 13:04:21 2014

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

\>>> ====================== RESTART ================================
>>> I was listening to 爱情买卖. Thu Apr 17 13:11:27 2014I was at the 阿凡达! Thu Apr 17 13:11:27 2014 I was listening to 爱情买卖. Thu Apr 17 13:11:31 2014 I was at the 阿凡达! Thu Apr 17 13:11:32 2014 all over Thu Apr 17 13:11:37 2014

==========================================================

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is the argument tuple for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing

anything else to the thread.