示例 1: 基本线程创建
# 示例 1: 基本线程创建
import threading
import time
def print_numbers():
for i in range(5):
time.sleep(1)
print(i)
# 创建线程
thread = threading.Thread(target=print_numbers)
# 启动线程
thread.start()
# 等待线程完成(可选)
thread.join()
print("Thread has finished execution.")
示例 2: 多个线程
# 示例 2: 多个线程
import threading
import time
def print_numbers(thread_name):
for i in range(5):
time.sleep(1)
print("{}:{}".format(thread_name, i))
# 创建并启动多个线程
threads = []
for i in range(3):
thread = threading.Thread(target=print_numbers, args=("Thread-{}".format(i+1),))
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
print("All threads have finished execution.")
示例 3: 使用线程锁
# 示例 3: 使用线程锁
import threading
lock = threading.Lock()
shared_resource = 0
def increment_resource():
global shared_resource
for _ in range(100000):
with lock:
shared_resource += 1
threads = []
for _ in range(10):
thread = threading.Thread(target=increment_resource)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print("Final value of shared_resource:{}".format(shared_resource))
示例 4: 使用线程池
# 示例 4: 使用线程池
from concurrent.futures import ThreadPoolExecutor
def print_numbers(n):
for i in range(n):
print(i)
# 创建一个线程池,最多允许5个线程同时运行
with ThreadPoolExecutor(max_workers=5) as executor:
# 提交任务到线程池
futures = [executor.submit(print_numbers, 5) for _ in range(10)]
# 等待所有任务完成(可选)
for future in futures:
future.result()
print("All tasks have finished execution.")
示例 5: 线程间通信(使用队列)
# 示例 5: 线程间通信(使用队列)
"""
在这个示例中,我们使用了一个队列来在生产者线程和消费者线程之间进行通信。
生产者将项目放入队列中,而消费者从队列中取出项目进行处理。当生产者完成
生产后,它发送一个None作为结束信号给消费者,消费者收到信号后停止处理。
"""
import threading
import queue
import time
def producer(q):
for i in range(5):
item = "item-{}".format(i)
q.put(item)
print("Produced {}".format(item))
def consumer(q):
while True:
item = q.get()
# time.sleep(1)
if item is None:# 使用None作为结束信号
break
print("Consumed {}".format(item))
q.task_done()
q = queue.Queue()
producer_thread = threading.Thread(target=producer, args=(q,))
consumer_thread = threading.Thread(target=consumer, args=(q,))
producer_thread.start()
consumer_thread.start()
producer_thread.join()
q.put("None") # 发送结束信号给消费者
consumer_thread.join()
print("All items have been produced and consumed.")