生产者和消费者案例

来源:互联网 发布:ubantu安装mysql数据库 编辑:程序博客网 时间:2024/05/21 14:09

关键知识点

1.wait()方法


声明:

public final void wait()                throws InterruptedException抛出:     IllegalMonitorStateException - 如果当前线程不是此对象监视器的所有者。     InterruptedException - 如果在当前线程等待通知之前或者正在等待通知时,任何线程中断了当前线程。在抛出此异常时,当前线程的中断状态 被清除。

该方法在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待,且当前线程必须拥有此对象监视器。执行该方法时,会发布对此监视器的所有权(释放此监视器的锁,这一点与sleep()休眠不同)并等待,直到被notify等方法唤。

2.notify()方法


声明:

public final void notify()抛出:     IllegalMonitorStateException - 如果当前线程不是此对象监视器的所有者。

该方法是唤醒此对象监视器上等待的某个线程,若所有线程在此对象上等待,则唤醒某其中一个线程,这是任意的。直到当前线程放弃此对象上的锁定,才能继续执行被唤醒的线程,就是某线程释放锁之后才能够执行唤醒操作。

package com.manu;/* * 多线程共享数据 * 生产者消费者案例 */public class ProducterConsumerDemo {public static void main(String[] args) {Food f = new Food();Producter p = new Producter(f);Consumer  c = new Consumer(f);Thread t1 = new Thread(p);Thread t2 =   new Thread(c);t1.start();t2.start();}}//生产者class Producter implements Runnable{private Food food;public Producter(Food food){this.food = food;}@Overridepublic void run() {for(int i=0; i<10; i++){if(i%2==0){//food.setName("糖醋里脊");//try {//Thread.sleep(500);//} catch (InterruptedException e) {//e.printStackTrace();//}//food.setPrice(20);food.set("糖醋里脊", 20);}else{//food.setName("毛血旺");//try {//Thread.sleep(500);//} catch (InterruptedException e) {//e.printStackTrace();//}//food.setPrice(30);food.set("毛血旺", 30);}}}}//消费者class Consumer implements Runnable{private Food food;public Consumer(Food food){this.food = food;}@Overridepublic void run() {for(int i=0; i<10; i++){//try {//Thread.sleep(500);//} catch (InterruptedException e) {//e.printStackTrace();//}//System.out.println(food.getName()+"-->"+food.getPrice());food.get();}}}//共享数据class Food{private String name;private int price;private boolean flag = true;//true表示只生产不消费,false表示只消费不生产public Food(){super();}public Food(String name, int price){super();this.name  = name;this.price = price;}public String getName(){return name;}public void setName(String name){this.name = name;}public int getPrice(){return price;}public void setPrice(int price){ this.price = price;}public synchronized void set(String name, int price){if(flag == false){//表示只消费不生产try {this.wait();//导致当前线程等待,让出CPU,释放该监视器的锁} catch (InterruptedException e) {e.printStackTrace();}}this.name = name;try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}this.price = price;flag = false;this.notify();//唤醒在此对象监视器上等待的单个线程}public synchronized void get(){if(flag){//表示只生产不消费try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(this.getName()+"-->价格:"+this.getPrice());flag = true;this.notify();}

}

0 0