*/
class ResourceDemo05{
private String name;
private int count;
public boolean flag = false;
public synchronized void set(String name){
while(flag)
try {
this.wait();
} catch (Exception e) {}
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 (Exception e) {}
System.out.println(Thread.currentThread().getName()+"------"+this.name);
flag = false;
this.notifyAll();
}
}
class ProducerDemo05 implements Runnable{
private ResourceDemo05 resd05;
ProducerDemo05(ResourceDemo05 resd05){
this.resd05 = resd05;
}
@Override
public void run() {
while(true){
resd05.set("商品");
}
}
}
class ConsumerDemo05 implements Runnable{
private ResourceDemo05 resd05;
ConsumerDemo05(ResourceDemo05 resd05){
this.resd05 = resd05;
}
@Override
public void run() {
while(true){
resd05.out();
}
}
}
public class InputOutputThreadDemo05 {
public static void main(String[] args) {
ResourceDemo05 resd05 = new ResourceDemo05();
ProducerDemo05 pro = new ProducerDemo05(resd05);
ConsumerDemo05 con = new ConsumerDemo05(resd05);
//新需求一,在需求的基础上进行增加生产者和消费者,以两个生产者和两个消费者为例
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
Thread t3 = new Thread(pro);
Thread t4 = new Thread(con);