多线程编程
一.创建线程
# -*- coding: cp936 -*-
#多线程编程
import thread
def fun(n):
for i in range(n):
print i
thread.start_new_thread(fun,(9,));
thread.start_new_thread(fun,(9,));
thread.start_new_thread(fun,(9,));
import threading
class mythread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num
def run(self):
print 'I am ',self.num
def run(x,y):
for i in range(x,y):
print i
'''
>>> t1 = threading.Thread(target=run,args=(15,20))
>>> ti.start()
'''
二.Thread对象中的方法
1.join方法
join方法:
如果一个线程或者函数的执行过程中调用另一个线程,并且待其完成操作之后才能执行,那么可以调用join方法
import threading
import time
class Mythread(threading.Thread):
def __init__(self,id):
threading.Thread.__init__(self)
self.id = id
def run(self):
x=0
time.sleep(60)
print self.id
def func():
t.start()
for i in range(5):
print i
>>> t=Mythread(2)
>>> func()
0
1
2
3
4
输出结果中没有线程的输出,func函数没有等待线程完成。
将程序更改为
import threading
import time
class Mythread(threading.Thread):
def __init__(self,id):
threading.Thread.__init__(self)
self.id = id
def run(self):
x=0
time.sleep(60)
print self.id
def func():
t.start()
<span style="color:#ff0000;"> t.join()
</span> for i in range(5):
print i
>>> t=Mythread(3)
>>> func()
3
0
1
2
3
4
调用join方法,等待线程完成
2.isAlive方法
查看线程是否运行
import threading
import time
class Mythread(threading.Thread):
def __init__(self,id):
threading.Thread.__init__(self)
self.id = id
def run(self):
x=0
time.sleep(10)
print self.id
def func():
t.start()
print t.isAlive()
>>> t=Mythread(3)
>>> func()
True
>>> 3
3.用setName方法设置线程名,用getName方法获得线程名
4.setDaemon方法
当需要主线程退出时,不管子线程是否完成都随主线程退出,则可以使用Thread对象的setDaemon方法来设置。
import threading
import time
class Mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name = threadname)
def run(self):
time.sleep(5)
print self.getName()
def func1():
t1.start()
print 'func1 done'
def func2():
t2.start()
print 'func2 done'
t1 = Mythread('t1')
t2 = Mythread('t2')
t2.setDaemon(True)
func1()
func2()