python 多线程编程

来源:互联网 发布:深圳安健科技知乎 编辑:程序博客网 时间:2024/06/07 22:50

python实现多线程的两种方法:

  1. 使用thread.start_new_thread方法开启多线程,运行指定方法。
  2. 创建类,继承threading.Thread类,重写__init__和run方法。启动线程执行的代码在run方法中。

使用thread.start_new_thread实现多线程,代码示例:
# author : YangWanimport threadimport timedef print_current_time(thread_name, delay_number):    count = 0    while count < 10:        time.sleep(delay_number)        print thread_name + str(time.ctime(time.time()))        count += 1try:    thread.start_new_thread(print_current_time, ('the first print clock thread', 5, ))    thread.start_new_thread(print_current_time, ('the second print clock thread', 10, ))except Exception, e:    print str(e)while True:    pass
注解:上面程序通过thread_new_thread启动两个线程,第一个每隔5秒打印当前时间,第二个每隔10秒打印当前时间。

通过继承threading.Thread类实现多线程,代码示例:
# author : YangWanimport threadingimport timeclass mythread (threading.Thread):    def __init__(self, thread_name, delay_number, threadID):        threading.Thread.__init__(self)        self.thread_name = thread_name        self.delay_number = delay_number        self.threadID = threadID    def run(self):        print 'the thread is started'        print 'thread_ID: %s' % self.threadID        print 'thread_name: %s' % self.thread_name        print_thread_time(self.thread_name, self.delay_number, self.threadID)        print 'the thread stoping'def print_thread_time(thread_name, delay_number, threadID):    print "This is the %d Thread" % threadID    count = 0    while count < 10:        print thread_name, repr(time.ctime(time.time()))        count += 1        time.sleep(delay_number)thread1 = mythread('Yangwan', 3, 1)thread2 = mythread('LanLan ', 2, 2)thread3 = mythread('Xiaoxiao', 10, 3)thread1.start()thread2.start()thread3.start()print 'starting my thread!'
注解:上启动三个线程,间隔打印当前时间。



原创粉丝点击