Python threading 并发 面向对象

import random
import time
from threading import Thread


class MyThread(Thread):
    def __init__(self, name):
        Thread.__init__(self)
        self.name = name

    def run(self):
        try:
            getattr(MyThread, self.name)
            names = 'self.{0}'.format(self.name)
            eval(names)()
        except Exception as e:
            print e


    def test_1(self):
        print '{} start'.format(self.name)
        time.sleep(random.randrange(1, 5))
        print '{} end'.format(self.name)

    def test_2(self):
        print '{} start'.format(self.name)
        time.sleep(random.randrange(1, 5))
        print '{} end'.format(self.name)


if __name__ == '__main__':
    t1 = MyThread('test_1')
    t2 = MyThread('test_2')
    t1.start()
    t2.start()

Python中有一个内置的threading模块,可以实现多线程并发编程。同时,Python也提供了一些高层次的并发工具,如asyncio库,可以实现基于协程的并发编程。 下面是一个使用面向对象方式完成多线程并发的示例代码: ```python import threading class CountThread(threading.Thread): def __init__(self, start_num, end_num): threading.Thread.__init__(self) self.start_num = start_num self.end_num = end_num self.count = 0 def run(self): for i in range(self.start_num, self.end_num): self.count += i def get_count(self): return self.count if __name__ == "__main__": threads = [] num_threads = 4 num_calcs = 10000000 for i in range(num_threads): start_num = i * num_calcs end_num = (i + 1) * num_calcs thread = CountThread(start_num, end_num) threads.append(thread) for thread in threads: thread.start() for thread in threads: thread.join() total_count = 0 for thread in threads: total_count += thread.get_count() print("Total count: {}".format(total_count)) ``` 在这个示例中,我们定义了一个CountThread类,继承了threading.Thread类,并且实现了run方法和get_count方法。在run方法中,我们对给定范围内的所有数字进行求和操作,并将结果保存在count属性中。在get_count方法中,我们返回count属性的值。 在主程序中,我们创建了num_threads个CountThread对象,并将它们保存在一个列表中。然后,我们启动所有的线程,并等待所有线程执行完毕。最后,我们将所有线程的count属性相加,得到最终的求和结果。 这个示例代码使用了面向对象方式实现了多线程并发编程,通过继承threading.Thread类,我们可以很方便地创建多个线程,并且可以在每个线程中定义自己的数据和方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值