public class Demo{
public static void main(String[] args){
Resource r = new Resource();
Producer p = new Producer(r);
Consumer c = new Consumer(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class Resource {
String name;
int count = 1;
boolean flag = true;
public void set(String name){
while(true){
if(flag){
synchronized(this){
this.name = name+count++;
System.out.println(Thread.currentThread().getName()+this.name+"....."+"生产");
flag = false;
}
}
}
}
public void out(){
while(true){
if(!flag){
synchronized(this){
System.out.println(Thread.currentThread().getName()+name+"..."+"消费");
flag = true;
}
}
}
}
}
class Producer implements Runnable{
private Resource r;
Producer(Resource r){
this.r = r;
}
public void run(){
r.set("商品");
}
}
class Consumer implements Runnable{
private Resource r;
Consumer(Resource r){
this.r = r;
}
public void run(){
r.out();
}
} |
|