生产者和消费者:当生产者在生产时,消费者等待。生产者生产完毕,唤醒消费者,消费者消费。消费者消费时,生产者等待,消费者消费完毕,唤醒生产者生产。实现代码如下:
//生产者和消费者 class Info { private String str1="中国"; private String str2="武汉"; public boolean flag=false; public synchronized void setStr1(String str1){ //set方法 this.str1=str1; } public synchronized void setStr2(String str2){ //set方法 this.str2 = str2; } public synchronized String getStr1(){ //get方法 return this.str1; } public synchronized String getStr2(){ //get方法 return this.str2; } //统一的set方法,进行一次设置 public synchronized void set(String str1,String str2){ if(flag){ try{ super.wait(); //不可生产,等待 }catch(InterruptedException e){ e.printStackTrace(); } } this.setStr1(str1); this.setStr2(str2); System.out.println("设置完成"); flag=true; //修改标志位 try{ Thread.sleep(300); //在唤醒线程之前先休息300mm } catch(InterruptedException e){ e.printStackTrace(); } super.notify(); //唤醒线程 } //统一的get方法,进行一次资源取出 public synchronized void get(){ if(!flag){ try{ super.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } System.out.println("取出"+this.getStr1()+"----->"+this.getStr2()); flag=false; //修改标志位 try{ Thread.sleep(300); //在唤醒线程之前先休息300mm } catch(InterruptedException e){ e.printStackTrace(); } super.notify(); } } class Producter implements Runnable { private Info info = null; public Producter(Info info){ this.info = info; } private boolean flag2=true; public void run(){ for(int i=0;i<50;i++){ if(flag2){ info.set("中国","武汉"); flag2=false; }else{ info.set("美国","纽约"); flag2=true; } } } } class Consumer implements Runnable { private Info info=null; public Consumer(Info info){ this.info = info; } public void run(){ for(int i=0;i<50;i++){ this.info.get(); } } } public class Demo26 { public static void main(String args[]){ Info info = new Info(); Producter p = new Producter(info); Consumer c = new Consumer(info); Thread tp = new Thread(p); Thread tc = new Thread(c); tp.start(); tc.start(); } }
这这里使用了notify进行唤醒,关于notify的使用,通过查阅API其定义是:“唤醒在此对象监视器上等待的单个线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。选择是任意性的,并在对实现做出决定时发生。线程通过调用其中一个 wait
方法,在对象的监视器上等待。 ”结合以上代码不难理解,notify在Info类内进行的调用,Info产生的对象是所有线程共同监听的对象。本程序中定义了两个线程,此两个线程共同监听互相唤醒。
生产者和消费的定义不难理解,关键问题是对代码的理解,