package test.itheima;
public class ProducConDemo {
/**
* @param args
*/
public static void main(String[] args) {
Resource r=new Resource();
Generator g=new Generator(r);
Consumer c=new Consumer(r);
Thread t1=new Thread(g);
Thread t2=new Thread(c);
Thread t3=new Thread(g);
Thread t4=new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName() + "---生产者"
+ this.name);
flag = true;
this.notifyAll();
}
public synchronized void out(String name) {
while (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "------消费者"
+ this.name);
flag = false;
this.notifyAll();
}
}
class Generator implements Runnable {
private Resource res;
Generator(Resource res) {
this.res = res;
}
public void run() {
while (true) {
res.set("+商品 +");
}
}
}
class Consumer implements Runnable {
private Resource res;
Consumer(Resource res) {
this.res = res;
}
public void run() {
while (true) {
res.out("+消费 +");
}
}
}
[黑马程序员]多线程_1.5之前,生产者,消费者
最新推荐文章于 2015-08-15 00:00:36 发布