模块有两个:threading和thread
thread模块实现多线程:
a=0
def funt(no,b):
global a
while True:
a+=1
print 'thread no %d = %d' %(no,a)
def funt(no,b):
global a
while True:
a+=1
print 'thread no %d = %d' %(no,a)
def test():
thread.start_new_thread(funt,(1,2))
thread.start_new_thread(funt,(2,2))
time.sleep(10)
if __name__=='__main__':
test()
threading模块实现多线程:
import threading
import time
import time
count =0
class aa(threading.Thread):
def __init__(self, no,interval):
threading.Thread.__init__(self)
self.no=no
self.interval=interval
self.isstop=False
def run(self):
global count
while not self.isstop:
count+=1
print 'thread %d-- count %d' %(self.no,count)
time.sleep(self.interval)
def stop(self):
self.isstop=True
def factory():
t1=aa(1,1)
t2=aa(2,2)
t1.start()
t2.start()
time.sleep(20)
t1.stop()
t2.stop()
if __name__=='__main__':
factory()
thread模块比较简单,使用thread.start_new_thread(funt,(1,2))方法传入一个函数和参数元组即可
threading模块比较灵活,需要继承threading.Thread类,通过重写方法修改运行代码run(),线程和java类似通过t1.start()启动