使用生产者模式和消费者模式实现交替输出: 假设只有两个线程,输出以下结果 t1 ---> 1 t2 --- >2 t1 ---> 3 t2 ---> 4
时间: 2024-02-24 20:56:01 浏览: 26
好的,我可以帮你解决这个问题。你可以使用一个共享的队列来实现。其中一个线程作为生产者,负责往队列中添加数据,另一个线程作为消费者,负责从队列中取出数据并输出。
以下是一个简单的 Python 代码示例:
```python
import threading
import time
queue = []
condition = threading.Condition()
class ProducerThread(threading.Thread):
def run(self):
global queue
nums = range(1, 5)
global condition
for num in nums:
condition.acquire()
queue.append(num)
print("t1 --->", num)
condition.notify()
condition.release()
time.sleep(1)
class ConsumerThread(threading.Thread):
def run(self):
global queue
global condition
while True:
condition.acquire()
if not queue:
print("t2 waiting")
condition.wait()
print("t2 notified")
num = queue.pop(0)
print("t2 --->", num)
condition.release()
time.sleep(1)
producer = ProducerThread()
consumer = ConsumerThread()
producer.start()
consumer.start()
```
在这个示例中,我们定义了一个队列和一个条件变量 `condition`。生产者线程 `ProducerThread` 负责往队列中添加数据,并在添加完数据后使用 `notify()` 方法通知消费者线程 `ConsumerThread` 可以取出数据了。消费者线程则负责从队列中取出数据并输出。
使用 `acquire()` 和 `release()` 方法来加锁和解锁,保证线程安全。当队列为空时,消费者线程会调用 `wait()` 方法等待通知。
运行这个程序,你会得到以下输出:
```
t1 ---> 1
t2 waiting
t1 ---> 2
t2 notified
t2 ---> 1
t1 ---> 3
t2 waiting
t1 ---> 4
t2 notified
t2 ---> 2
t2 ---> 3
t2 ---> 4
```
可以看到,两个线程交替输出了所需的结果。