forked from kingname/SourceCodeofMongoRedis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_by_python.py
More file actions
41 lines (32 loc) · 953 Bytes
/
Copy pathqueue_by_python.py
File metadata and controls
41 lines (32 loc) · 953 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import time
import random
from queue import Queue
from threading import Thread
class Producer(Thread):
def __init__(self, queue):
super().__init__()
self.queue = queue
def run(self):
while True:
a = random.randint(0, 10)
b = random.randint(90, 100)
print(f'生产者生产了两个数字:{a}, {b}')
self.queue.put((a, b))
time.sleep(2)
class Consumer(Thread):
def __init__(self, queue):
super().__init__()
self.queue = queue
def run(self):
while True:
num_tuple = self.queue.get(block=True)
sum_a_b = sum(num_tuple)
print(f'消费者消费了一组数,{num_tuple[0]} + {num_tuple[1]} = {sum_a_b}')
time.sleep(random.randint(0, 10))
queue = Queue()
producer = Producer(queue)
consumer = Consumer(queue)
producer.start()
consumer.start()
producer.join()
consumer.join()