public class Goods {//商品类 //私有属性 private String brand;//品牌 private String name;//商品的名称 private boolean flag;//标识是否有商品,默认值是false,代表没有商品, //公有的取值,赋值方法 public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getName() { return name; } public void setName(String name) { this.name = name; } //生产商品的方法 public synchronized void produc(String brand,String name){ if (flag) {//flag的值为false时,没有商品,生产者生产商品,如果flag的值为true时,代表有商品,生产者等待 try { super.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//调用的是Object类中的wait方法 }//被唤醒后,代表没有商品了,没有商品就开始生产 this.brand=brand;//局部变量的值赋值给成员变量 try { Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.name=name; System.out.println("生产者生产了"+this.brand+"----------------"+this.name); /**商品生产结束*/ flag=true; super.notify();//通知消费者线程 } //消费者取走商品的同步方法 public synchronized void custom(){ if (flag==false) {//没有商品时,消费者等待, try { super.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//没有商品时,消费者等待 }//有商品时,取走商品 try { Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("--------------------消费者取走了商品-----------"+this.brand+"==========="+this.name); /**商品已取走*/ flag=false; super.notify(); } } //生产者线程 public class Producer implements Runnable { //共享资源作为类的属性有属性 private Goods g; //带参构造方法 public Producer(Goods g) { super(); this.g = g; } @Override public void run() {//生产者要做的事情是生产商品 for (int i = 0; i <10; i++) { if (i%2==0) {//偶数 //调用生产商品的方法 g.produc("娃哈哈", "矿泉水"); }else {//奇数 g.produc("旺仔", "小馒头"); } } } } package cn.bjsxt.pc3; //生产者线程 public class Producer implements Runnable { //共享资源作为类的属性有属性 private Goods g; //带参构造方法 public Producer(Goods g) { super(); this.g = g; } @Override public void run() {//生产者要做的事情是生产商品 for (int i = 0; i <10; i++) { if (i%2==0) {//偶数 //调用生产商品的方法 g.produc("娃哈哈", "矿泉水"); }else {//奇数 g.produc("旺仔", "小馒头"); } } } } //消费者的线程-->负责取商品 public class Customer implements Runnable { //共享资源是商品 private Goods gg;//共享资源作为线程类的私有属性 //带参构造方法 public Customer(Goods gg) { super(); this.gg = gg; } @Override public void run() {//这是消费者线程,负责取走商品 for (int i = 0; i <10; i++) { //调用取走的同步方法 gg.custom(); } } } public class Test { public static void main(String[] args) { /**1.创建共享资源的对象*/ Goods g=new Goods(); /**2.创建生产者线程的对象*/ Producer p=new Producer(g); /**3.创建消费者线程的对象*/ Customer c=new Customer(g); //启动两个线程 new Thread(p).start();//启动生产者线程 new Thread(c).start();//启动消费者线程 } }