此类表示在单独的控制线程中运行的活动,有两种方法可以指定该活动,一是将可调用对象传递给构造函数,二是通过覆盖子类中的run()方法。

  如果你对线程不太理解,我们可以打个比方,把线程数看作车辆数,我们来完成一个简单的客运运输工作(以下为了方便理解,也加入相应注释)。

  更多threading模块函数和对象说明,可参考:https://www.cnblogs.com/leozhanggg/p/10317494.html

一、无线程:
示例:
import time
start = time.time()
people = 500 # 假设有500个人
def action(num):
global people
while people>0:
people -= 50 # 每次运输50人
print("车辆编号:%d, 当前车站人数:%d" %(num, people))
time.sleep(1) num = 1 # 车辆编号
action(num)
end = time.time()
print("Duration time: %0.3f" %(end-start))
运行结果:
C:\Python37\python.exe Y:/Project-python/threading/test.py
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
Duration time: 10.001 Process finished with exit code

二、单线程:
编码示例:
import threading
import time
start = time.time()
people = 500 # 假设有500个人
def action(num):
global people
while people>0:
people -= 50 # 每次运输50人
print("车辆编号:%d, 当前车站人数:%d" %(num, people))
time.sleep(1) num = 1 # 车辆编号
vehicle = threading.Thread(target=action, args=(num,)) # 新建车辆
vehicle.start() # 启动车辆
vehicle.join() # 检查到站车辆 end = time.time()
print("Duration time: %0.3f" %(end-start))
运行结果:
C:\Python37\python.exe Y:/Project-python/threading/test.py
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
Duration time: 10.001 Process finished with exit code
三、多线程(传递对象方式):
编码示例:
# -*- coding: utf-8 -*
import threading
import time people = 500 # 假设有500个人
def action(num):
global people
while people>0:
people -= 50 # 每次运输50人
print("车辆编号:%d, 当前车站人数:%d" %(num, people))
time.sleep(1) start = time.time()
vehicles = [] # 新建车辆组
for num in range(5):
vehicle = threading.Thread(target=action, args=(num,)) # 新建车辆
vehicles.append(vehicle) # 添加车辆到车辆组中 for vehicle in vehicles:
vehicle.start() # 分别启动车辆 for vehicle in vehicles:
vehicle.join() # 分别检查到站车辆
end = time.time()
print("Duration time: %0.3f" % (end-start))
运行结果:
C:\Python37\python.exe Y:/Project-python/threading/test.py
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
Duration time: 2.001 Process finished with exit code

四、多线程(覆盖子类方式)

编码示例:

# -*- coding: utf-8 -*
import threading
import time people = 500
class MyThread(threading.Thread):
def __init__(self, num):
super(MyThread, self).__init__()
self.num = num def run(self):
global people
while people > 0:
people -= 50
print("车辆编号:%d, 当前车站人数:%d " % (self.num, people))
time.sleep(1) start = time.time()
vehicles = [] # 新建车辆组
for num in range(5): # 设置车辆数
vehicle = MyThread(num) # 新建车辆
vehicles.append(vehicle) # 添加车辆到车辆组中
vehicle.start() #启动车辆 for vehicle in vehicles:
vehicle.join() # 分别检查到站车辆
end = time.time()
print("Duration time: %0.3f" % (end-start))

运行结果:

C:\Python37\python.exe Y:/Project-python/threading/test.py
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数:
车辆编号:, 当前车站人数: 车辆编号:, 当前车站人数:100车辆编号:, 当前车站人数: 车辆编号:, 当前车站人数:
Duration time: 2.003 Process finished with exit code

五、结果分析

  

  1. 通过结果不难发现,不使用线程类和使用单线程运行时间是一样的,因为我们正常执行一个脚本,本质上就是单线程。

  2. 创建多线程的两种方法运行时间也是一样的,因为最终都是交给Thread类来处理,自行选择即可。

  3. 多线程运行时间明显比单线程快的多,从理论上来说是和线程数成正比的,但是实际并非是线程越多越好,因为线程越多所消耗的资源也就越多。

六、有关该类的其他说明:

    a. 创建线程对象后,必须通过调用线程的start()方法启动其活动,这将在单独的控制线程中调用run()方法。

    b. 一旦线程的活动开始,线程就被认为是“活着的”,当run()方法终止时,它会停止活动,或者引发异常。

    c. 线程可以调用is_alive()方法测试是否处于活动状态,其他线程可以调用线程的join()方法,这将阻塞调用线程,直到调用其join()方法的线程终止。

    d. 线程有一个名称,这个名称可以传递给构造函数,并通过name属性读取或更改。

    e. 线程可以标记为“守护程序线程”,这个标志的意义在于,当只剩下守护进程线程时,整个Python程序都会退出,可以通过守护程序属性设置该标志。

----- 转载请注明原作,谢谢:https://www.cnblogs.com/leozhanggg/p/10335098.html

Python-Thread(通俗易懂)的更多相关文章

  1. TLS 与 python thread local

    TLS 先说TLS( Thread Local Storage),wiki上是这么解释的: Thread-local storage (TLS) is a computer programming m ...

  2. Python Thread related

    1.Thread.join([timeout]) Wait until the thread terminates. This blocks the calling thread until the ...

  3. python thread的join方法解释

    python的Thread类中提供了join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行.这个方法还可以设定一个timeout参数,避免无休止的等待.因为两个线程顺序完成,看起来象一个 ...

  4. 【Python@Thread】queue模块-生产者消费者问题

    python通过queue模块来提供线程间的通信机制,从而可以让线程分项数据. 个人感觉queue就是管程的概念 一个生产者消费者问题 from random import randint from ...

  5. 【Python@Thread】Semaphore&糖果机

    信号量适用与多线程竞争有限资源的情况. from atexit import register from time import ctime, sleep from threading import ...

  6. 【Python@Thread】锁示例

    当出现竞态条件时候,即在同一个时刻只有一个线程可以进入临界区,需要使用同步. 常见的同步原语有两种:锁/互斥,信号量. 锁是最简单,最低级的机制. 首先看一个不使用锁时候的多线程示例: from at ...

  7. 【Python@Thread】threading模块

    theading模块的Thread类 属性: name 线程名 ident 线程标识符 daemon  布尔值,标示是否为守护线程 方法: __init__(target=None, name=Non ...

  8. 【Python@Thread】thread模块

    一.关于Python多线程 Python解释器中可以同时运行多个线程,但是再任意时刻只能有一个线程在解释器运行. Python虚拟机的访问是由全局解锁器(GIL)控制的,由GIL保证同时只有一个线程的 ...

  9. Python thread local

    由于GIL的原因,笔者在日常开发中几乎没有用到python的多线程.如果需要并发,一般使用多进程,对于IO Bound这种情况,使用协程也是不错的注意.但是在python很多的网络库中,都支持多线程, ...

  10. test for python thread

    #!/usr/bin/python # -*- coding: UTF-8 -*- import thread import time # 为线程定义一个函数 def print_time(threa ...

随机推荐

  1. useradd和groupadd(Linux创建用户\用户组\设置\分配用户权限\多用户远程登录权限)的使用

    前言: man useradd man  groupadd info useradd info  groupadd 都可以获取相关命令的用法信息. 个人比较喜欢读英文解释文档,没有你想象的那么comp ...

  2. 20155219付颖卓《网络攻防》Exp4 恶意代码分析

    一.基础问题回答 如果在工作中怀疑一台主机上有恶意代码,但只是猜想,所有想监控下系统一天天的到底在干些什么.请设计下你想监控的操作有哪些,用什么方法来监控. 可以用window7自带的schtasks ...

  3. RobotFramework-RIDE环境搭建一:关于Python2和Python3的共存使用

    最近在搭建Robot Framework自动化测试框架,由于Robot Framework 框架是基于Pytho语言开发的,要想使用Robot Framework 首先需要有Python环境. RID ...

  4. python,验证码生成

    <pre>import string import random from PIL import Image from PIL import ImageDraw from PIL impo ...

  5. NPOI设置单元格背景色

    NPOI设置单元格背景色在网上有好多例子都是设置为NPOI内置的颜色值 但是想用rgb值来设置背景色,即:通过HSSFPalette类获取颜色值时会抛出异常:Could not Find free c ...

  6. vue-cli项目在IE下运行钩子函数抛出异常“ReferenceError: “Promise”未定义&quot;”的解决办法

    兼容IE是个坑,低版本IE很多都没法跑起来 问题现象:vue-cli项目在IE下运行,会在钩子函数出现 ReferenceError: “Promise”未定义 解决办法: step1:安装最新的we ...

  7. Vector Math for 3D Computer Graphics (Bradley Kjell 著)

    https://chortle.ccsu.edu/VectorLessons/index.html Chapter0 Points and Lines (已看) Chapter1 Vectors, P ...

  8. Java扩展方法之SPI

    API:API(Application Programming Interface)表示应用程序编程接口 SPI:SPI(Service Provider Interface)表示服务提供商接口  A ...

  9. 剑指offer 6.查找和排序 旋转数组的最小数字

    题目描述 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转. 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素. 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋 ...

  10. python中使用 C 类型的数组以及ctypes 的用法

    Python 在 ctypes 中为我们提供了类似C语言的数据类型, 它的用途(我理解的)可能是: (1) 与 其他语言(如 C.Delphi 等)写的动态连接库DLL 进行交换数据,因为 pytho ...