📄 testproducercomsumer.java
字号:
package chapter13;
public class TestProducerComsumer {
public static void main(String[] args) {
AppleBox ms = new AppleBox();
Thread t1 = new AddAppleThread(ms);
Thread t2 = new EatAppleThread(ms);
t1.start();
t2.start();
}
}
class AppleBox {
private int[] data = new int[5];
private int index = 0;
public synchronized void Add(int c) {
while (index == data.length) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
data[index] = c;
index++;
System.out.println(c + " be Add!");
this.notifyAll();
print();
}
public synchronized void Eat() {
while (index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
break;
}
}
index--;
System.out.println(data[index] + " be Eat!");
data[index] = 0;
this.notifyAll();
print();
}
public void print() {
for (int i = 0; i < data.length; i++) {
if (data[i] != 0)
System.out.print(data[i] + "***");
}
System.out.println("");
}
}
class AddAppleThread extends Thread {
AppleBox ms;
public AddAppleThread(AppleBox ms) {
this.ms = ms;
}
public void run() {
for (int i = 1; i <= 26; i++) {
ms.Add(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
}
class EatAppleThread extends Thread {
AppleBox ms;
public EatAppleThread(AppleBox ms) {
this.ms = ms;
}
public void run() {
for (int i = 1; i <= 26; i++) {
ms.Eat();
try {
Thread.sleep(800);
} catch (InterruptedException e) {
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -