简单的创建多线程
import threading # 导入模块 import time def xian1(): for i in range(3): print("老子是第一") time.sleep(1) def xian2(): for i in range(3): print("老子是第二") time.sleep(1) def main(): t1 = threading.Thread(target=xian1) t2 = threading.Thread(target=xian2) t1.start() t2.start() if __name__ == '__main__': main()
用继承threading模块创建多线程类
import threading # 导入模块 import time class A(threading.Thread): #创建一个类继承threading模块 def run(self): for i in range(3): print("老子是第一") time.sleep(1) class B(threading.Thread): def run(self): for i in range(3): print("老子是第二") time.sleep(1) def main(): t1 = A() t2 = B() t1.start() t2.start() t2.run1().start() if __name__ == '__main__': main()
多线程 创建锁
import threading # 导入模块 import time glock = threading.Lock() # 创建锁 value = 0 def run (): global value # 上锁 glock.acquire() for x in range(1000000): value += 1 print(value) glock.release() # 解锁 def main(): for i in range(2): t1 = threading.Thread(target=run) t1.start() if __name__ == '__main__': main()
多线程,生产与消费模式
import threading import random import time # 设置总钱数 zongmony = 1000 # 创建锁 glock = threading.Lock() # 次数 times = 0 class scz(threading.Thread): def run(self): global zongmony global times while True: # 随机生产一些钱 mony = random.randint(100, 1000) # 生产好后建立锁, glock.acquire() # 判断是否生产了十次 if times >10: glock.release() break zongmony += mony times +=1 print("生产者生产了%d元,总共有%d元" %(mony,zongmony)) # 执行完以后释放锁 glock.release() time.sleep(0.5) class xfz(threading.Thread): def run(self): global zongmony global times while True: # 随机消费一些钱 xiaofei = random.randint(100, 1000) glock.acquire() if xiaofei <zongmony: zongmony -=xiaofei print("消费者消费%d元,剩余%d元"%(xiaofei , zongmony)) else : if times >10: glock.acquire() break print("余额不足!!") time.sleep(0.5) glock.release() def main(): for i in range(5): t = scz() t.start() if i >= 2: t1 = xfz() t1.start() if __name__ == '__main__': main()