堆栈

堆栈

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]; // 数据弹出栈,标号为valuecakechild线程取走

}

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将生产到的标号为valuecake放入栈

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值