常见术语及用法
基本使用
# 定义线程类 class MyThread(threading.Thread): def __init__(self): super(MyThread, self).__init__() # 或 threading.Thread.__init__(self) def run(self) -> None: tid = threading.currentThread().ident tname = threading.currentThread().getName() print("===== 线程开始: id: %d, name: %s" % (tid, tname)) # 线程休眠 time.sleep(5) print("===== 线程结束: id: %d, name: %s" % (tid, tname)) print("主线程: id: %d, name: %s" % (threading.currentThread().ident, threading.currentThread().name)) # 创建线程 thread1 = MyThread() # 启动线程 thread1.start() # 主线程等待thread1线程结束 thread1.join() print("主线程退出")
线程同步
多个人从苹果箱子里取苹果吃(这个苹果箱比较特殊,类似抽奖箱,一次只能伸一只手进去,且规定一次只能拿一个苹果)
import threading import time import random class AppleBox: def __init__(self, apple_num: int): self.apple_num = apple_num self.res_lock = threading.Lock() def get(self): while True: self.res_lock.acquire() tid = threading.currentThread().ident tname = threading.currentThread().getName() t_apple_num = self.apple_num print("===== 线程: id: %d, name: %s, 从箱子里拿到了%s号苹果, 走到边上开始吃苹果" % (tid, tname, t_apple_num)) self.apple_num -= 1 is_empty = self.apple_num <= 0 self.res_lock.release() # 线程休眠, 模拟吃苹果时间 time.sleep(random.randint(3, 5)) print("===== 线程: id: %d, name: %s, 吃完%s号苹果" % (tid, tname, t_apple_num)) if is_empty: break class MyThread(threading.Thread): def __init__(self, apple_box: AppleBox): super(MyThread, self).__init__() # 或 threading.Thread.__init__(self) self.apple_box = apple_box def run(self) -> None: self.apple_box.get() apple_box = AppleBox(5) thread_list = [] for i in range(3): # 创建线程 thread1 = MyThread(apple_box) # 启动线程 thread1.start() thread_list.append(thread1) # 主线程等待上面的线程执行完毕 for t in thread_list: t.join() print("退出主线程")
参考
Java并发编程基础:线程与同步 - 知乎 (zhihu.com)
走进并发,线程同步与线程通信全解析 - 知乎 (zhihu.com)
Java 生产者和消费者3种实现方式_用java实现生产者消费者_小博要变强啊~的博客-CSDN博客
标签:apple,Python,self,threading,num,线程,thread1,使用,多线程 From: https://www.cnblogs.com/sailJs/p/17576747.html