packagedemo;classResource2{privateStringname;privateintcount=1;privatebooleanflag=false;publicsynchronizedvoidset(Stringname){if(flag)try{wait();}catch(InterruptedExcepti...
package demo;
class Resource2 {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name) {
if (flag)
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
this.name = name;
count++;
flag = true;
notify();
}
public synchronized void out() {
if (flag)
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(Thread.currentThread().getName() + "\tname:" + name);
flag = false;
notify();
}
}
class Producer implements Runnable {
private Resource2 r;
public Producer(Resource2 r) {
super();
this.r = r;
}
public void run() {
while (true) {
r.set("小苍");
}
}
}
class Consumer implements Runnable {
Resource2 r;
public Consumer(Resource2 r) {
super();
this.r = r;
}
public void run() {
while (true) {
r.out();
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Resource2 r = new Resource2();
Producer p = new Producer(r);
Consumer c = new Consumer(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
展开