帮忙看看一个Java小程序 哪里出了问题.........

jinwei 发布于 2011/05/15 17:05
阅读 243
收藏 1

代码如下, 其中使用index 作为篮子中剩余馒头数, 可是运行结果发现 明显打印出的篮子中剩余馒头数有问题,求教,为什么呀?

-----------------------------------------------------------------------


public class ProducerConsumer {

public static void main(String[] args){

LanZi lz = new LanZi();

Producer Tom = new Producer(lz,"Tom");

Consumer Jack = new Consumer(lz,"Jack");

Producer Masking = new Producer(lz,"Masking");

Consumer Jack222 = new Consumer(lz,"Jack222");

Thread t1 = new Thread(Tom);

Thread t2 = new Thread(Jack);

Thread t3 = new Thread(Masking);

Thread t4 = new Thread(Jack222);

Thread t5 = new Thread(Tom);

t1.start();

t2.start();

t3.start();

t4.start();

t5 .start();

}

}

 

class ManTou{

int id;

ManTou(int id){

this.id = id;

}

}

 

class LanZi{

int index = 0;

ManTou[] mtarr = new ManTou[6];

public synchronized void putin(ManTou mt){

while(index == mtarr.length){

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

this.notifyAll();

mtarr[index] = mt;

index++;

}

public synchronized void getout(){

while(index == 0){

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

this.notifyAll();

index--;

mtarr[index] = null;

}

}

 

class Producer implements Runnable{

String name;

LanZi  lz;

Producer(LanZi lz,String name){

this.lz = lz;

this.name = name;

}

public void run(){

int i = 0;

while(true){

lz.putin(new ManTou(i));

System.out.println("\n-----------生产者: "+this.name+" 生产了馒头"+i + "\t\t\t\t\t\t---篮子中现有"+(lz.index)+"个馒头");

i++;

try {

Thread.sleep((long)(Math.random()*50));

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

 

class Consumer implements Runnable{

String name;

LanZi  lz;

Consumer(LanZi lz,String name){

this.lz = lz;

this.name = name;

}

public void run(){

int i = 0;

while(true){

lz.getout();

System.out.println("\n-----------消费者: "+this.name+" 吃掉了馒头"+i+ "\t\t\t\t\t\t---篮子中现有"+lz.index+"个馒头" );

i++;

try {

Thread.sleep((long)(Math.random()*50));

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

 

 

代码如上,其中使用index 作为篮子中剩余馒头数, 可是运行结果发现 明显打印出的篮子中剩余馒头数有问题,求教,为什么呀?

加载中
0
黄钦钦
黄钦钦

在getout()方法和putin()方法中打印出index来,System.out.println("putin:"+index);发现问题

其实getout()和putin()方法中的index是正确显示的,只是外面打印的时候出了问题。。Producer

类和Consumer类不能

正确反映出index的值来,有可能调用一个getout方法-1后,再调用putin方法+1,然后在类中打印出来,LZ

可以自己比较内部打印和外部打印的区别,就能看出问题了。。。

OSCHINA
登录后可查看更多优质内容
返回顶部
顶部