本帖最后由 孙传磊 于 2013-3-8 11:37 编辑
下面是一个根据毕老师视频写出的代码
关于生产者与消费者的代码:
class Resource {
private String name;
private int count=1;
boolean flag=false;
public synchronized void set(String name) {
while(flag)
try {
this.wait();
} catch (InterruptedException e) {e.printStackTrace();}
this.name = name+"^"+count++;
System.out.println(Thread.currentThread().getName()+"*生产者*"+this.name);
flag=true;
this.notifyAll();
}
public synchronized void out() {
while(!flag)
try {
this.wait();
} catch (InterruptedException e) {e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"^^^^消费者^^^^"+this.name);
flag=false;
this.notifyAll();
}
}
class Producer implements Runnable{
private Resource r;
Producer(Resource r){
this.r=r;
}
public void run(){
while(true){
r.set("+商品+");
}
}
}
class Consumer implements Runnable{
private Resource r;
Consumer(Resource r){
this.r=r;
}
public void run(){
while(true){
r.out();
}}
}
class RCThread1{
public static void main(String[] args){
Resource r=new Resource();
Producer p =new Producer(r);
Consumer c =new Consumer(r);
new Thread(p).start();
new Thread(p).start();
new Thread(c).start();
new Thread(c).start();
}
}
上面的代码 设想 输出的结果是:生产者 与 消费者轮流输出,及下面这种情况
Thread-1*生产者*+商品+^65650
Thread-2^^^^消费者^^^^+商品+^65650
Thread-0*生产者*+商品+^65651
Thread-3^^^^消费者^^^^+商品+^65651
Thread-1*生产者*+商品+^65652
Thread-2^^^^消费者^^^^+商品+^65652
Thread-0*生产者*+商品+^65653
Thread-3^^^^消费者^^^^+商品+^65653
Thread-1*生产者*+商品+^65654
Thread-2^^^^消费者^^^^+商品+^65654
Thread-0*生产者*+商品+^65655
Thread-3^^^^消费者^^^^+商品+^65655
Thread-1*生产者*+商品+^65656
Thread-2^^^^消费者^^^^+商品+^65656
Thread-0*生产者*+商品+^65657
Thread-3^^^^消费者^^^^+商品+^65657
Thread-1*生产者*+商品+^65658
Thread-2^^^^消费者^^^^+商品+^65658
Thread-0*生产者*+商品+^65659
Thread-3^^^^消费者^^^^+商品+^65659
Thread-1*生产者*+商品+^65660
Thread-2^^^^消费者^^^^+商品+^65660
当将上面的程序放在eclipse上运行 当点击控制台 右边的 终止 按钮是 时却出现了,重复打印的现象,
显现如下:
Thread-3^^^^消费者^^^^+商品+^52764
Thread-1*生产者*+商品+^52765
Thread-2^^^^消费者^^^^+商品+^52765
Thread-2^^^^消费者^^^^+商品+^52765
Thread-0*生产者*+商品+^52766
Thread-2^^^^消费者^^^^+商品+^52766
Thread-1*生产者*+商品+^52767
Thread-3^^^^消费者^^^^+商品+^52767
Thread-1*生产者*+商品+^52768
Thread-1*生产者*+商品+^52768
Thread-2^^^^消费者^^^^+商品+^52768
Thread-0*生产者*+商品+^52769
Thread-2^^^^消费者^^^^+商品+^52769
Thread-1*生产者*+商品+^52770
现在很迷茫的是不知道是程序写得有问题, 还是eclipse在被点击 终止 按钮 时产生的打印错误?如何解决?
|