堆栈

本文介绍了一个使用Java实现的同步堆栈模拟程序,该程序通过两个线程分别扮演烘焙师(cooker)和孩子(child),模拟了烘焙师制作蛋糕并将其放入堆栈,而孩子则从堆栈中取出蛋糕的过程。堆栈的容量固定为10个蛋糕,当堆栈为空时,烘焙师需等待;当堆栈满时,孩子需等待。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

堆栈

classcakeStack{

privateintvalue=0;//堆栈指针指向栈底表示栈内没有cake

privateint[]cakeBag=newint[10];//堆栈有10个字符的空间,定义cake栈的大小为10

publicsynchronizedintget(){//加锁

while(value==0){//指针指向栈底,堆栈没有cake,没有数据可以出栈

try{

this.wait();//等待cooker线程把cake放入栈,child线程处于等待状态

}catch(InterruptedExceptione){

}

}

this.notify();//解锁唤醒处于等待状态的线程

value--;//指针向下移动

returncakeBag[value];//数据弹出栈,标号为valuecakechild线程取走

}

publicsynchronizedvoidput(intc){//加锁

while(value==cakeBag.length){//栈满,不能压栈

try{

this.wait();//栈满,暂时cooker不生产cake,等待有child取蛋糕

}catch(InterruptedExceptione){

}

}

this.notify();//解锁

cakeBag[value]=c;//数据入栈,cooker将生产到的标号为valuecake放入栈

value++;//指针向上移动,栈中内容加1

}

}

classcookerimplementsRunnable{//cooker类

cakeStacktheStack;//cooker类生成的cake都放到同步堆栈中

publiccooker(cakeStacks){

theStack=s;

}

publicvoidrun(){

intc;

for(inti=0;;i++){//生产随机次

c=(int)(Math.random()*10);//随机产生10个数字,表示不同标号的cake

theStack.put(c);//把不同标号的cake入栈

System.out.println("cookermake:\t"+c);

try{

Thread.sleep((int)(Math.random()*1000));

}catch(InterruptedExceptione){

}

}

}

}

classchildimplementsRunnable{//child类

cakeStacktheStack;//child类获得的字符都来自同步堆栈

publicchild(cakeStacks){

theStack=s;

}

publicvoidrun(){

intc;

for(inti=0;;i++){

c=theStack.get();//child类从堆栈中读取数据

System.out.println("childeat:\t"+c);

try{

Thread.sleep((int)(Math.random()*1000));

}catch(InterruptedExceptione){

}

}

}

}

publicclassStackTest{

publicstaticvoidmain(Stringargs[]){

cakeStackstack=newcakeStack();

Threadcooker=newThread(newcooker(stack));

Threadchild=newThread(newchild(stack));

System.out.println("Person\t\tcakeMark");

cooker.start();

child.start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值