Python 多线程
来源:互联网 发布:医院数据质量分析报告 编辑:程序博客网 时间:2024/06/14 10:31
一、介绍
线程是操作系统能够进行运算调度的最小单位。
Python的标准库提供了两个模块:thread
和threading
,thread
是低级模块,threading
是高级模块,对thread
进行了封装,只需要使用threading
这个高级模块。
import time, threading# 新线程执行的代码:def loop(): print 'thread %s is running...' % threading.current_thread().name n = 0 while n < 5: n = n + 1 print 'thread %s >>> %s' % (threading.current_thread().name, n) time.sleep(1) print 'thread %s ended.' % threading.current_thread().nameprint 'thread %s is running...' % threading.current_thread().namet = threading.Thread(target=loop, name='LoopThread')t.start()t.join()print 'thread %s ended.' % threading.current_thread().name
启动一个线程就是把一个函数传入并创建
Thread
实例,然后调用start()
开始执行。由于任何进程默认就会启动一个线程,我们把该线程称为主线程,主线程又可以启动新的线程,Python的threading
模块有个current_thread()
函数,它永远返回当前线程的实例。主线程实例的名字叫MainThread
,子线程的名字在创建时指定,我们用LoopThread
命名子线程。名字仅仅在打印时用来显示,完全没有其他意义,如果不起名字Python就自动给线程命名为Thread-1
,Thread-2
……
二、使用线程
1、线程的创建
import threadingimport timedef run(n): print("task", n) time.sleep(1) print('2s') time.sleep(1) print('1s') time.sleep(1) print('0s') time.sleep(1)if __name__ == "__main__": t1 = threading.Thread(target=run, args=("t1",)) t2 = threading.Thread(target=run, args=("t2",)) t1.start() t2.start()
2、继承threading.Thread来自定义线程类,其本质是重构Thread类中的run方法
import threadingimport timeclass MyThread(threading.Thread): def __init__(self, n): super(MyThread, self).__init__() # 重构run函数必须要写 self.n = n def run(self): print("task", self.n) time.sleep(1) print('2s') time.sleep(1) print('1s') time.sleep(1) print('0s') time.sleep(1)if __name__ == "__main__": t1 = MyThread("t1") t2 = MyThread("t2") t1.start() t2.start()点击打开链接
阅读全文
0 0
- Python多线程
- Python多线程
- Python多线程
- python多线程
- python 多线程
- python多线程
- python多线程
- python 多线程
- python多线程
- Python多线程
- Python 多线程
- python多线程
- python 多线程
- {python多线程}
- Python 多线程
- Python多线程
- python 多线程
- Python 多线程
- http请求头和响应头
- Flex 布局教程:实例篇
- WebLogic如何设置session超时时间
- 采样与还原
- Java设计模式及六大原则
- Python 多线程
- Jupyter Notebook 的快捷键
- vue router-link 上添加点击事件
- 数组 阶乘 循环 20170723
- HANDLE句柄初识和颜色相关
- python中 list和tuple 、dict和set区别
- iOS开发- 添加地址从通讯录中选择添加(firstName,lastName真机为nil,模拟器正常)
- Dropwizard与Spring Boot比较
- React中state与props比较