堆栈
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];//数据弹出栈,标号为value的cake被child线程取走
}
publicsynchronizedvoidput(intc){//加锁
while(value==cakeBag.length){//栈满,不能压栈
try{
this.wait();//栈满,暂时cooker不生产cake,等待有child取蛋糕
}catch(InterruptedExceptione){
}
}
this.notify();//解锁
cakeBag[value]=c;//数据入栈,cooker将生产到的标号为value的cake放入栈
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();
}
}