5个python多线程简单示例

示例 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.")


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值