多线程
CPU:
程序:代码指令集合
进程:程序的执行过程
线程:指令执行的最小单位
线程安全
非线程安全
线程锁–互斥锁
同步
异步
继承方式实现多线程
线程的状态(生命周期)
创建状态----->就绪状态----->运行状态----->死亡状态
| |
| 挂起状态 |
'''
import threading
def demo(name):
for i in range(10):
print(name,i)
t1 = threading.Thread(target=demo,args=("小宇",))
t2 = threading.Thread(target=demo,args=("小霍",))
t1.start()
t2.start()
'''
'''
import threading
#import time
def run(name):
for i in range(1,101):
print(name,"跑了:",i,"米")
# time.sleep(1)
p1 = threading.Thread(target=run,args=("小红",))
p2 = threading.Thread(target=run,args=("小绿",))
p3 = threading.Thread(target=run,args=("小名",))
p1.start()
p2.start()
p3.start()
'''
'''
import threading
import time
list = []
def cun(name):
while True:
list.append("方便面")
print(name,"存了一袋方便面,仓库剩余",len(list))
# time.sleep(1)
def qu(name):
while True:
if len(list) == 0:
time.sleep(1)
else:
list.pop()
print(name, "取了一袋方便面,仓库剩余", len(list))
# time.sleep(1)
p1 = threading.Thread(target=cun,args=("p1",))
p2 = threading.Thread(target=cun,args=("p2",))
p3 = threading.Thread(target=cun,args=("p3",))
p4 = threading.Thread(target=qu,args=("p4",))
p5 = threading.Thread(target=qu,args=("p5",))
p6 = threading.Thread(target=qu,args=("p6",))
p7 = threading.Thread(target=qu,args=("p7",))
p1.start()
p2.start()
p3.start()
p4.start()
p5.start()
p6.start()
p7.start()
'''
'''
import threading,time
list = []
for i in range(100):
list.append("烤冷面")
def qu(name):
while len(list) > 0:
list.pop()
print(name, "取了一份烤冷面,仓库剩余", len(list))
p1 = threading.Thread(target=qu,args=("p1",))
p2 = threading.Thread(target=qu,args=("p2",))
p3 = threading.Thread(target=qu,args=("p3",))
p1.start()
p2.start()
p3.start()
'''
'''
#继承
import threading
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
for i in range(100):
print(i)
t1 = MyThread()
t2 = MyThread()
t1.start()
t2.start()
'''
'''
import threading,time
lock = threading.Lock()
list = ["烤冷面"]
def get():
#获取锁
lock.acquire()
if len(list) > 0:
time.sleep(1)
list.pop()
print("取走一份")
#释放锁
lock.release()
t1 = threading.Thread(target=get)
t2 = threading.Thread(target=get)
t3 = threading.Thread(target=get)
t1.start()
t2.start()
t3.start()
'''
#两进三出的线程
import threading,time
lockq = threading.Lock()
lockc = threading.Lock()
list = []
class MyThread(threading.Thread):
def __init__(self,name):
threading.Thread.__init__(self)
self._name = name
def run(self):
if self._name == "取货人":
while True:
self.qu()
time.sleep(1)
else:
while True:
self.cun()
time.sleep(0.5)
def cun(self,):
lockc.acquire()
list.append("货")
print("存一份货,剩余",len(list))
lockc.release()
def qu(self):
lockq.acquire()
if len(list) > 0:
list.pop()
print("取一份货,剩余",len(list))
lockq.release()
t1 = MyThread("存货人")
t2 = MyThread("存货人")
t3 = MyThread("取货人")
t4 = MyThread("取货人")
t5 = MyThread("取货人")
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()