threading 常见用法:

(1) 在 thread 中,我们是通过 thread.start_new_thread(function, args) 来开启一个线程,接收一个函数和该函数的参数,函数的参数必须是元组的形式
(2) 在 threading 中,我们是通过 threading.Thread(target=function, args=(....)) 来创建一个对象,然后再通过对象的 start() 方法来开启一个线程,多个线程可以并发执行

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def fun():
print time.ctime()
time.sleep(1) for i in range(3):
t = threading.Thread(target=fun, args=()) # 创建一个 Thread 对象,接收一个函数和该函数的参数
t.start() # 通过对象来开启一个新的线程,通过线程来执行函数
[root@localhost ~]$ python 1.py    # 多个线程并发执行,只需要执行一秒
Mon Jan 28 21:15:35 2019
Mon Jan 28 21:15:35 2019
Mon Jan 28 21:15:35 2019

threading 有两种方法可以开启一个新的线程:

(1) 如上面的例子,通过创建 Thread 对象,然后通过对象的 start() 方法来运行一个新的线程
(2) 第二种方法是继承 threading.Thread 这个类, 然后重写 run() 方法来运行一个新的线程

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading class MyThread(threading.Thread): def __init__(self):
threading.Thread.__init__(self) def run(self):
print time.ctime()
time.sleep(1) for i in range(3):
t = MyThread()
t.start()
[root@localhost ~]$ python 1.py
Mon Jan 28 23:53:02 2019
Mon Jan 28 23:53:02 2019
Mon Jan 28 23:53:02 2019

threading.Lock():用于创建一个锁对象,我们可以同时开启多个线程,但是在任意时刻只能有一个线程能在解释器运行,因此需要由全局解锁器(GIL)控制运行哪个线程

锁对象的常用方法如下:

lock = threading.Lock() 创建一个锁对象
    lock.acquire() 锁上锁,当某个线程被锁上之后,会优先执行这个锁的内容,直到锁释放才会执行其他线程
    lock.locked() 查看锁的状态,如果已经被锁上了则返回True,否则返回False
    lock.release() 释放锁,必须先获得锁才能释放锁

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def hello():
for i in range(3):
hello_lock.acquire()
print('hello'),
time.sleep(1)
world_lock.release() def world():
for i in range(3):
world_lock.acquire()
print('world')
time.sleep(1)
hello_lock.release() hello_lock = threading.Lock()
world_lock = threading.Lock() world_lock.acquire()
t1 = threading.Thread(target=hello, args=())
t2 = threading.Thread(target=world, args=()) t1.start()
t2.start()
[root@localhost ~]$ python 1.py
hello world
hello world
hello world

其他常用方法:

t.join()方法用于阻塞下一个线程的运行,等待当前线程执行完再执行下一个线程,例子如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def fun():
print time.ctime()
time.sleep(1) for i in range(3):
t = threading.Thread(target=fun, args=())
t.start()
t.join()
[root@localhost ~]$ python 1.py     # 由于线程被阻塞,需要执行3秒
Mon Jan 28 21:33:35 2019
Mon Jan 28 21:33:36 2019
Mon Jan 28 21:33:37 2019

t.setDaemon()方法用于设置当前线程随着主线程的退出而退出,例子如下:

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def fun(): # 函数的功能是打印三次当前时间
for i in range(3):
print time.ctime()
time.sleep(1) t = threading.Thread(target=fun, args=())
t.setDaemon(True)
t.start() print 'End...' # 执行 print 之后,主线程就退出了,最终结果只会打印一次
[root@localhost ~]$ python 1.py
Mon Jan 28 21:54:48 2019
End...

t.getName() 用于获取线程的名字,t.setName() 用于重新设置线程的名字,默认的线程名是 Thread-1,Thread-2,Thread-3,......

#!/usr/bin/env python
#-*- coding:utf-8 -*- import time
import threading def fun():
newName = 'new-' + t.getName()
print newName
time.sleep(1) for i in range(3):
t = threading.Thread(target=fun, args=())
t.start()
[root@localhost ~]$ python 1.py
new-Thread-1
new-Thread-2
new-Thread-3

多线程模块:threading的更多相关文章

  1. 基于Python的多线程模块Threading小结

    步入正题前,先准备下基本知识,线程与进程的概念. 相信作为一个测试人员,如果从理论概念上来说其两者的概念或者区别,估计只会一脸蒙蔽,这里就举个例子来说明下其中的相关概念. 平安夜刚过,你是吃到了苹果还 ...

  2. Python并发复习2 - 多线程模块threading

    一.多线程的调用 threading 模块建立在thread 模块之上.thread模块以低级.原始的方式来处理和控制线程,而threading 模块通过对thread进行二次封装, 提供了更方便的a ...

  3. 用生动的案例一步步带你学会python多线程模块

    鱼和熊掌不可兼得 鱼,我所欲也,熊掌,亦我所欲也,二者不可得兼,舍鱼而取熊掌者也. 从6月开始写公众号,连着四个月一直尽量保证一周五更,结果整天熬夜搞的身体素质骤降.十一休假决定暂时将公众号放放,好好 ...

  4. python笔记9 线程进程 threading多线程模块 GIL锁 multiprocessing多进程模块 同步锁Lock 队列queue IO模型

    线程与进程 进程 进程就是一个程序在一个数据集上的一次动态执行过程.进程一般由程序.数据集.进程控制块三部分组成.我们编写的程序用来描述进程要完成哪些功能以及如何完成:数据集则是程序在执行过程中所需要 ...

  5. python-网络安全编程第六天(threading多线程模块&Queue模块&subprocess模块)

    前言 昨天晚上9点多就睡了 2点起来没睡意... 那就学习吧emmmm ,拿起闲置几天的python课程学习.学习到现在5.58了 总结下 继续开始学习新的内容 多多线程? 线程(英语:thread) ...

  6. Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块

    Python第十五天  datetime模块 time模块   thread模块  threading模块  Queue队列模块  multiprocessing模块  paramiko模块  fab ...

  7. Python线程模块threading

    线程,程序执行的最小单元,单线程处理多个任务只能一个处理完后继续处理下一个直到全部处理完,多线程处理任务会比单线程处理起来快吗?在python程序里得看情况,首先有GIL锁的存在导致同一时刻只能有一个 ...

  8. Python多线程模块

    引言 thread threading 1 Thread 11 下面使用threading模块实现与上面相同的功能 12 在创建新线程时还可以给Thread传递可调用类的对象这样使用类本身来保存信息 ...

  9. 多线程模块的同步机制event对象

    多线程模块的同步机制event对象 线程的核心特征就是他们能够以非确定的方式(即何时开始执行,何时被打断,何时恢复完全由操作系统来调度管理,这是用户和程序员无法确定的)独立执行的,如果程序中有其他线程 ...

  10. Python的多线程(threading)与多进程(multiprocessing )

    进程:程序的一次执行(程序载入内存,系统分配资源运行).每个进程有自己的内存空间,数据栈等,进程之间可以进行通讯,但是不能共享信息. 线程:所有的线程运行在同一个进程中,共享相同的运行环境.每个独立的 ...

随机推荐

  1. ajax 和xmlHttpRequest区别

    什么是 ajax ajax 即“Asynchronous JavaScript and XML”(异步 JavaScript 和 XML),也就是无刷新数据读取. http 请求 首先需要了解 htt ...

  2. dp之二维背包poj1837(天平问题 推荐)

    题意:给你c(2<=c<=20)个挂钩,g(2<=g<=20)个砝码,求在将所有砝码(砝码重1~~25)挂到天平(天平长  -15~~15)上,并使得天平平衡的方法数..... ...

  3. TOMCA源码分析——处理请求分析(上)

    在<TOMCAT源码分析——请求原理分析(上)>一文中已经介绍了关于Tomcat7.0处理请求前作的初始化和准备工作,请读者在阅读本文前确保掌握<TOMCAT源码分析——请求原理分析 ...

  4. android——inflater 用法(转)

    在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...

  5. /dev/sdxx is apparently in use by the system; will not make a filesystem here! 解决方法

    在存储上共享了一个500G的空间,映射到Linux系统提供上,环境由2个节点组成. 一. 测试一: 直接mount 用fdisk 格式化之后如下: [root@rac1 u01]# fdisk -l ...

  6. GPU硬件加速原理 /转

    现代浏览器大都可以利用GPU来加速页面渲染.每个人都痴迷于60桢每秒的顺滑动画.在GPU的众多特性之中,它可以存储一定数量的纹理(一个矩形的像素点集合)并且高效地操作这些纹理(比如进行特定的移动.缩放 ...

  7. Hibernate- 子查询

    01.搭建开发环境 02.子查询 package com.gordon.test; import java.util.List; import org.hibernate.Session; impor ...

  8. javascript-限制文本框只输入数字

    使用onInput()事件 oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素通过 ...

  9. 6款强大的 jQuery 网页布局创建及优化插件

    本文将为您介绍6款功能强大的jQuery插件,它们能够帮助您方便快捷地创建复杂的网络布局并进行优化. 1.UI.Layout 该插件可以创建任何你想要的UI形式:包括从简单的标题或侧边栏,到一个包含工 ...

  10. python with妙用

    class aa(): def bb(self): print("hhhh") return "hello world" def __enter__(self) ...