python 多线程编程

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

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

使用thread.start_new_thread实现多线程,代码示例:
# author : YangWan
import thread
import time
def 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 += 1

try:
    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 : YangWan
import threading
import time

class 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!'
注解:上启动三个线程,间隔打印当前时间。



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值