堆栈
class cakeStack {
private int value = 0; // 堆栈指针指向栈底 表示栈内没有cake
private int[] cakeBag = new int[10]; // 堆栈有10个字符的空间,定义cake栈的大小为10
public synchronized int get() { // 加锁
while (value == 0) { // 指针指向栈底,堆栈没有cake,没有数据可以出栈
try {
this.wait(); // 等待cooker线程把cake放入栈,child线程处于等待状态
} catch (InterruptedException e) {
}
}
this.notify(); // 解锁唤醒处于等待状态的线程
value--; // 指针向下移动
return cakeBag[value]; // 数据弹出栈,标号为value的cake被child线程取走
}
public synchronized void put(int c) { // 加锁
while (value == cakeBag.length) { // 栈满,不能压栈
try {
this.wait(); // 栈满,暂时cooker不生产cake,等待有child取蛋糕
} catch (InterruptedException e) {
}
}
this.notify();// 解锁
cakeBag[value] = c; // 数据入栈,cooker将生产到的标号为value的cake放入栈
value++; // 指针向上移动,栈中内容加1
}
}
class cooker implements Runnable { // cooker类
cakeStack theStack; // cooker类生成的cake都放到同步堆栈中
public cooker(cakeStack s) {
theStack = s;
}
public void run() {
int c;
for (int i = 0;; i++) {// 生产随机次
c = (int) (Math.random() * 10); // 随机产生10个数字,表示不同标号的cake
theStack.put(c); // 把不同标号的cake入栈
System.out.println("cooker make: \t " + c);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
}
}
class child implements Runnable { // child类
cakeStack theStack; // child类获得的字符都来自同步堆栈
public child(cakeStack s) {
theStack = s;
}
public void run() {
int c;
for (int i = 0;; i++) {
c = theStack.get(); // child类从堆栈中读取数据
System.out.println("child eat:\t" + c);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
}
}
public class StackTest {
public static void main(String args[]) {
cakeStack stack = new cakeStack();
Thread cooker = new Thread(new cooker(stack));
Thread child = new Thread(new child(stack));
System.out.println("Person\t\tcakeMark");
cooker.start();
child.start();
}
}