python多线程的基本使用

python下实现多线程有两种方式:一种是通过函数的方式产生新的线程,另外一种是通过面向对象的方式实现

通过调用thread模块中的start_new_thread()函数来产生新线程

 

#!/usr/bin/env python
#encoding:utf-8
#author:zhxia
import thread
import time

thread_count=0;
def test(num,interval):
        for x in xrange(1,10):
           print 'current thread is:%d,and x is:%d'%(num,x)
           time.sleep(interval)
        thread.exit_thread()

if __name__=='__main__':
        thread.start_new_thread(test,(1,1))
        thread.start_new_thread(test,(2,1))
        thread.start_new_thread(test,(3,1))
        #为了防止主线程在子线程之前退出,需要检测当前的子线程数目,直到所有的子线程执行完毕
        time.sleep(0.001) #必需sleep一下,否则取不到子线程的数目
        while thread._count()>0:
                time.sleep(0.5)

 

通过threading模块实现:

#!/usr/bin/env python
#encoding:utf-8
#author:zhxia
import time
import threading
import sys
class test(threading.Thread):
        def __init__(self,num,interval):
                threading.Thread.__init__(self)
                self.thread_num=num
                self.interval=interval
        def run(self):
                for x in xrange(1,9):
                        print 'current thread is %d,and x is %d'%(self.thread_num,x)
                        time.sleep(self.interval)

if __name__=='__main__':
        t1=test(1,1)
        t2=test(2,1)
        t3=test(3,1)
        t1.start();
        t2.start();
        t3.start();

 

 

 

 

posted @ 2012-12-11 13:12  涛光  阅读(605)  评论(0编辑  收藏  举报