天天看點

當輸入為多個,輸出為多個時(多線程)

public class Resource {

private String name;

private int count=1;

private boolean flag=false;


public synchronized   void setName(String name) {

while(flag){

try {

wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

this.name = name+"--"+count++;

System.out.println(Thread.currentThread().getName()+"...生産者..."+this.name);

    flag=true;

    this.notifyAll();

}

private  synchronized  void out() {

// TODO Auto-generated method stub

while(!flag){

     
  try {

wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

        }

        System.out.println(Thread.currentThread().getName()+"...消費者..."+this.name);

    flag=false;

    this.notifyAll();

}

 }      
o