public class Resource {
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"..生产者.."+count++);
}
this.name = 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()+"......消费者......"+count++);
}
flag = false;
this.notifyAll();
}
public static void main(String[] args){
Resource r = new Resource();
Prodecter pro = new Prodecter(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}
}
class Prodecter implements Runnable{
private Resource r;
private int count = 1;
private boolean flag = false;
public Prodecter(Resource r ){
super();
this.r= r ;
}
public void run(){
for(int x=0;x<1000;x++){
r.set("商品");
}
}
}
class Consumer implements Runnable{
private Resource r;
private int count = 1;
private boolean flag = false;
public Consumer(Resource r ){
super();
this.r= r ;
}
public void run(){
for(int x=0;x<1000;x++){
if(x%2==0){
r.out();
}
}
}
}
|
|