多线程-综合练习

消费者与生产者

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.xiaobai.shangguigu.Test;


class Clerk {//店员
private int productNum = 0;//产品的数量

public synchronized void addProductNum() {
if (productNum > 20) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else {
productNum++;
System.out.println(Thread.currentThread().getName() + "生产了第" + productNum + "个产品");
notifyAll();
}
}

public synchronized void minusProductNum() {
if (productNum <= 0) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} else {
System.out.println(Thread.currentThread().getName() + "消费了第" + productNum + "个产品");
productNum--;
notifyAll();
}

}
}

class Producer extends Thread {//生产者
private Clerk clerk;

public Producer(Clerk clerk) {
this.clerk = clerk;
}

@Override
public void run() {
while (true) {
System.out.println("生产者开始生产");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
clerk.addProductNum();
}
}
}

class Consumer extends Thread {//消费者
private Clerk clerk;

public Consumer(Clerk clerk) {
this.clerk = clerk;
}

@Override
public void run() {
while (true) {
System.out.println("消费者正在消费");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
clerk.minusProductNum();
}
}
}

//生产者和消费者实例
public class ProducerConsumerTest {


public static void main(String[] args) {
Clerk clerk = new Clerk();
Producer producer = new Producer(clerk);
Consumer consumer = new Consumer(clerk);
producer.setName("生产者1");
consumer.setName("消费者1");
producer.start();
consumer.start();
}
}

多线程-综合练习
http://blog.170827.xyz/2024/03/09/多线程-综合练习/
作者
XIAOBAI
发布于
2024年3月9日
许可协议