python 多线程示例
import queue
import time
import threading
import threading
from datetime import datetime
# 创建一个线程安全的队列
q = queue.Queue()
def print_thread_id():
thread_id = threading.current_thread().ident
print(f"Current thread ID: {thread_id}")
# 生产者线程函数,往队列中放入数据
def producer(y):
for i in range(10):
data = f"Data {y}:{i}"
q.put(data)
print("Produced", data)
# 消费者线程函数,从队列中获取数据
def consumer():
while True:
data = q.get()
time.sleep(1)
if q.empty():
now = datetime.now()
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)
break
thread_id = threading.current_thread().ident
print("Consumed", data, thread_id)
q.task_done()
def ping_threading():
threads = []
for i in range(10):
thread = threading.Thread(target=consumer)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
## 生产消息
for i in range(5):
producer(i)
ping_threading()
print("END")