python 多线程编程
来源:互联网 发布:深圳安健科技知乎 编辑:程序博客网 时间:2024/06/07 22:50
python实现多线程的两种方法:
- 使用thread.start_new_thread方法开启多线程,运行指定方法。
- 创建类,继承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!'
注解:上启动三个线程,间隔打印当前时间。
阅读全文
1 0
- Python多线程编程
- Python多线程编程
- Python多线程编程
- python 多线程编程
- python 多线程编程
- zt:python多线程编程
- Python多线程编程
- Python多线程编程
- Python多线程编程
- Python多线程编程
- python 多线程编程
- python 多线程编程
- python sqlite多线程编程
- python 多线程编程
- python多线程编程
- python多线程编程
- python 多线程编程
- python多线程编程
- 【算法题】找出两个只出现奇数次的数字
- 数据结构 图
- 【Studio】登录Android Studio
- Sublime Text快捷键列表
- Android 绘制圆形头像
- python 多线程编程
- 触发器的实践案例
- 解决ScrollView嵌套RecyclerView的冲突,非常简单,拿去可以直接用
- jQuery之异步Ajax请求使用
- php使用phpqrcode类库生成带图片LOGO的二维码
- Python打造漏洞扫描器 3
- Android 使用MVP模式 实现一个查询功能。
- Android根据不同身份配置APP对应的不同模块
- AngularJS 05(事件绑定)