📄 producerconsumer.java
字号:
public class ProducerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}
class Product {
int id;
Product(int id) {
this.id = id;
}
public String toString() {
return "Product-" + id;
}
}
class SyncStack {
int buffer = 0;
Product[] arrProducts = new Product[5];
public synchronized void push(Product wt) {
while (buffer == arrProducts.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
arrProducts[buffer] = wt;
buffer++;
}
public synchronized Product pop() {
while (buffer == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
buffer--;
return arrProducts[buffer];
}
}
class Producer implements Runnable {
SyncStack ss = null;
Producer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for (int i = 0; i < 10; i++) {
Product wt = new Product(i);
System.out.println("生产了:" + wt);
ss.push(wt);
try {
Thread.sleep((int) (Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
SyncStack ss = null;
Consumer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for (int i = 0; i < 10; i++) {
Product wt = ss.pop();
System.out.println("消费了: " + wt);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -