1、多线程类的继承

import threading
import time
class MyThreading(threading.Thread):
def __init__(self,n):
super(MyThreading,self).__init__()
self.n = n
def run(self):
print("threading %s"%(self.n))
time.sleep(2) threading1 = MyThreading("%s" %(1))
threading2 = MyThreading("%s" %(2))
threading1.start()
threading1.join() ## 1执行完才会执行2
threading2.start() E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test4.py
threading 1
threading 2
。。。。。。。

2、线程测试案例

import threading
import time
class MyThreading(threading.Thread):
def __init__(self,n):
super(MyThreading,self).__init__()
self.n = n
def run(self):
time.sleep(2)
print("threading %s"%(self.n)) threading1 = MyThreading("%s" %(1))
threading2 = MyThreading("%s" %(2))
threading1.start()
threading1.join() ## 1执行完才会执行2
threading2.start() print("main") E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test4.py
threading 1
main
threading 2

3、多线程时间测试案例

import threading
import time
list = [ ]
def run(i):
print("test %s"%(i))
time.sleep(2) starttime = time.time()
for i in range(1,50):
t1 = threading.Thread(target=run,args=(i,))
t1.start()
list.append(t1) for i in list :
i.join() print("end") endtime = time.time()
print("cost:", endtime-starttime) E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
end
cost: 2.007871150970459 Process finished with exit code 0

 4、守护线程概念,默认情况下为非守护线程,即主线程推出前,需要等待所有的非守护线程结束放可以推出。而守护线程就表示这个线程“不重要”,即主线程结束时候,无需等待守护线程是否执行完成。

import threading
import time
list = [ ]
def run(i):
print("test %s"%(i))
time.sleep(5)
print("setDaemon end ") starttime = time.time()
for i in range(1,50):
t1 = threading.Thread(target=run,args=(i,))
# t1.setDaemon(True)
t1.start()
list.append(t1) print("main end")
E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
main end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end
setDaemon end Process finished with exit code 0 import threading
import time
list = [ ]
def run(i):
print("test %s"%(i))
time.sleep(5)
print("setDaemon end ") starttime = time.time()
for i in range(1,50):
t1 = threading.Thread(target=run,args=(i,))
t1.setDaemon(True)
t1.start()
list.append(t1) print("main end") E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
main end Process finished with exit code 0

5、GIL 和线程锁。GIL就是一把全局排他锁。他的作用就是保证同一时刻只有一个线程可以执行代码,对多线程有较大影响。

import threading
import time
lock = threading.Lock()
list = [ ] res = 0
def run(i):
# 在Python3.5中已经优化,结果都是50.在python2.7如果不加锁可能有一场
lock.acquire()
global res
res = res + 1
lock.release() starttime = time.time()
for i in range(0,50):
t1 = threading.Thread(target=run,args=(i,))
t1.setDaemon(True)
t1.start()
list.append(t1) for i in list:
i.join() print(res)

6、当有多重锁时候,可以使用Rlock,使用递归锁可以避免出现死锁的情况

7、信号量简单实用。信号量就相当于多把锁

# Author : xiajinqi
import threading
import time semaphore = threading.BoundedSemaphore() def run(i):
semaphore.acquire()
print("阮娇。。。。")
time.sleep()
semaphore.release() for i in range(,):
tt = threading.Thread(target=run,args=(i,))
tt.start()

8、event 在线程间简单应用,车子等红灯

# Author : xiajinqi
import threading
import time event = threading.Event() # - 绿灯 -20红灯,大于二十从0开始
def lighter():
count =
while True : if count >= and count < :
event.clear()
print("当前红灯")
count = count +
elif count >= :
count =
else :
event.set()
print("当前绿灯")
count +=
time.sleep()
def run():
while True :
time.sleep()
if event.is_set() : #event.waite( 如果没有值,就会一直卡主等待
print("开始过十字路口")
else :
print("开始等车")
event.wait() t1 = threading.Thread(target=lighter)
t2 = threading.Thread(target=run) t1.start()
t2.start()

9、队列queue和列表、元组的区别。二者都有顺序。但是从列表取一个数据,数据还存在。而队列取出一个数据以后,改数据在队列就会被清空。符合实际应用场景。队列有三种:一、先进先去 二、先进后去 三、可以设置优先级别的队

import queue

# 先进先去
qu= queue.Queue()
for i in range(1,5):
qu.put(i) while qu.qsize() >0:
print(qu.get()) # 先进后去
import queue # 先进先去
qu= queue.LifoQueue()
for i in range(1,5):
qu.put(i) while qu.qsize() >0:
print(qu.get()) E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/333.py
4
3
2
1 import queue # 具有优先级别的队列 .类型需要一样
qq= queue.PriorityQueue() list =[(1,"xiajinqi"),(1,"test"),(2,"test2"),(3,"test3"),(5,"test5"),(3,"test3")] for lt in list:
qq.put(lt) while qq.qsize() >0:
print(qq.get()) import queue # 具有优先级别的队列 .类型需要一样
qq= queue.PriorityQueue() list =[(1,"xiajinqi"),(1,"test"),(2,"test2"),(3,"test3"),(5,"test5"),(3,"test3")] for lt in list:
qq.put(lt) while qq.qsize() >0:
print(qq.get())

  

10、消费者生产者模型,解耦,相互不影响

import queue
import time
import threading
qu = queue.Queue(maxsize=) # 每次生产十个
def Producder():
while True:
for i in range(,):
print("生产了两个骨头")
qu.put("骨头 %s"%(i))
time.sleep() # 生产者消费者模型,多个人生产多个人消费。
def Consumer(name) :
while True:
print("%s 吃了一个骨头 %s"%(name,qu.get()))
time.sleep(0.5) #两个消费
c1 = threading.Thread(target=Consumer,args=("test1",))
c2 = threading.Thread(target=Consumer,args=("test2",))
pd1 = threading.Thread(target=Producder)
pd1.start()
c1.start()
c2.start()

多线程深入理解和守护线程、子线程、锁、queue、evenet等介绍的更多相关文章

  1. [Java][Android] 多线程同步-主线程等待全部子线程完毕案例

    有时候我们会遇到这种问题:做一个大的事情能够被分解为做一系列相似的小的事情,而小的事情无非就是參数上有可能不同样而已! 此时,假设不使用线程,我们势必会浪费许多的时间来完毕整个大的事情.而使用线程的话 ...

  2. Unity3d 创建线程 子线程与主线程通信

    创建子线程 一,不带参数 Thread   resourcesLoadThread=new Thread (this.resourceLoadTxt); resourcesLoadThread.Sta ...

  3. NSThread 子线程 Cocoa NSOperation GCD(Grand Central Dispatch) 多线程

    单词:thread 英 θred:n 线.思路.vt 穿过.vi 穿透过 一.    进程.线程 进程:正在进行中的程序被称为进程,负责程序运行的内存分配,每一个进程都有自己独立的虚拟内存空间 线程: ...

  4. Tasks遇到的一些坑,关于在子线程中对线程权限认证。

    一般情况下,不应该在执行多线程认证的时候对其子线程进行身份认证,如:A线程的子线程B和子线程C. 当使用 Parallel.ForEach方法时,只有自身线程能够拥有相对应的权限,其子线程权限则为NU ...

  5. Android——子线程操作主线程

    子线程不能直接操作主线程 UI线程 //水平进度条 public void jdt1_onclick(View view) { final ProgressDialog pd = new Progre ...

  6. C#子线程执行完后通知主线程

    其实这个比较简单,子线程怎么通知主线程,就是让子线程做完了自己的事儿就去干主线程的转回去干主线程的事儿. 那么怎么让子线程去做主线程的事儿呢,我们只需要把主线程的方法传递给子线程就行了,那么传递方法就 ...

  7. C#子线程执行完后通知主线程(转)

    其实这个比较简单,子线程怎么通知主线程,就是让子线程做完了自己的事儿就去干主线程的转回去干主线程的事儿.  那么怎么让子线程去做主线程的事儿呢,我们只需要把主线程的方法传递给子线程就行了,那么传递方法 ...

  8. 线程概念( 线程的特点,进程与线程的关系, 线程和python理论知识,线程的创建)

    参考博客: https://www.cnblogs.com/xiao987334176/p/9041318.html 线程概念的引入背景 进程 之前我们已经了解了操作系统中进程的概念,程序并不能单独运 ...

  9. python 全栈开发,Day41(线程概念,线程的特点,进程和线程的关系,线程和python 理论知识,线程的创建)

    昨日内容回顾 队列 队列 : 先进先出.数据进程安全 队列实现方式: 管道 + 锁 生产者消费者模型 : 解决数据供需不平衡 管道 双向通信 数据进程不安全 EOFError: 管道是由操作系统进行引 ...

随机推荐

  1. React学习笔记(七)条件渲染

    React学习笔记(七) 六.条件渲染 使用if或条件运算符来创建表示当前状态的元素. 可以使用变量来存储元素.比如: let button = null; if (isLoggedIn) { but ...

  2. Java学习---Quartz定时任务快速入门

    Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用.Quartz可以用来创建简单或为运行十个,百个, ...

  3. Mysql学习---使用Python执行存储过程

    使用Python执行存储过程 使用Python执行存储过程[2部分]: 1.执行存储过程,获取存储过程的结果集  2.将返回值设置给了  @_存储过程名_序号 = #!/usr/bin/env pyt ...

  4. [BZOJ 3441]乌鸦喝水

    3441: 乌鸦喝水 Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 374  Solved: 148[Submit][Status][Discuss] ...

  5. [T-ARA][거짓말(Part.1)][谎言(Part.1)]

    歌词来源:http://music.163.com/#/song?id=5403062 作曲 : 赵英秀 [作曲 : 赵英秀] 作词 : 安英民 [作词 : 安英民] 사랑한단 거짓말 보고싶을거란 ...

  6. windows下注册和取消pg服务的命令

    pg_ctl register [-N servicename] [-U username] [-P password] [-D datadir] [-w][-t seconds] [-o optio ...

  7. js oc与线程

    分属不同的线程 //定义需要暴露给js的内容,这里我们只暴露personName和queryPersonName接口 @protocol PersonProtocol <JSExport> ...

  8. tcp 面向连接

    TCP通信时通过三次握手建立连接,这个连接不是虚拟链路,每个IP报文是要寻址,通过路由转发的 那建立的这个连接能够起什么作用啊,感觉建立这个连接和不建立这个连接的效果是一样的啊!因为除去可靠性等机制, ...

  9. 远程调用内核接口的封装类(RCKObjs)

    RCK 包括 Application, Function, Connection, Command, Response 和 Fields 六 大类, 其主要功能例如以下:     a. Applica ...

  10. prority_queue自定义类型使用

    struct Tower{ Tower(int h, int p){ height = h; pos = p; } bool operator < (Tower &t) { if (he ...