java线程之一生产者与消费者
package com.itcast.threadinfo;
//生产者与消费者
//(1-1)
public class Demo1 {
?public static void main(String[] args) {
??proDemo p = new proDemo();
??Procedure pp = new Procedure(p);
??Customer cc = new Customer(p);
??Thread t1 = new Thread(pp);
??Thread t2 = new Thread(cc);
??t1.start();
??t2.start();
?}
}
class proDemo {
?private String name;
?private int count;
?private boolean flag = false;
?public synchronized void procudeInfo(String name) {
??if (flag)
???try {
????this.wait();
???} catch (InterruptedException e) {
????// TODO Auto-generated catch block
????e.printStackTrace();
???}
??this.name = name + count;
??count++;
??System.out.println("生成者..."+this.name);
??flag = true;
??notify();
?}
?public synchronized void getcustomer() {
??if (!flag)
???try {
????this.wait();
???} catch (InterruptedException e) {
????// TODO Auto-generated catch block
????e.printStackTrace();
???}
???System.out.println("消费者..."+name);
??flag = false;
??notify();
?}
}
class Procedure implements Runnable {
?proDemo d;
?public Procedure(proDemo d) {
??this.d = d;
?}
?@Override
?public void run() {
??while (true) {
???d.procudeInfo("烤鸭");
??}
?}
}
class Customer implements Runnable {
?proDemo d;
?public Customer(proDemo d) {
??this.d = d;
?}
?public void run() {
??while (true) {
???d.getcustomer();
??}
?}
}