- package cn.itcast.gz;
- /**
- * 消费者 生产者模式(线程间的通信)
- */
- public class ResourceDemo3 {
- public static void main(String[] args) {
- Resource3 r = new Resource3();
- Input3 input = new Input3(r);
- Output3 output = new Output3(r);
- Thread t1 = new Thread(input);
- Thread t2 = new Thread(output);
- t1.start();
- t2.start();
- }
- }
- class Resource3 {
- private String name;
- private String sex;
- private boolean flag=false;
- public synchronized void setInfo(String name,String sex)
- {
- if(flag)
- try{this.wait();}catch(Exception e){e.printStackTrace();};
- this.name = name;
- this.sex= sex;
- flag = true;
- notifyAll();
- }
- public synchronized void getInfo()
- {
- if(!flag)
- try{this.wait();}catch(Exception e){e.printStackTrace();};
- System.out.println("name: "+name +"sex: "+sex);
- flag = false;
- this.notifyAll();
- }
- }
- class Input3 implements Runnable
- {
- private Resource3 r;
- private int i=0;
- public Input3(Resource3 r)
- {
- this.r = r;
- }
- @Override
- public void run() {
- while(true)
- {
- if(i==0)
- {
- r.setInfo("小小", "女女女女女女");
- }
- else
- {
- r.setInfo("大大", "男");
- }
- i=(i+1)%2;
- }
- }
- }
- class Output3 implements Runnable
- {
- private Resource3 r;
- public Output3(Resource3 r)
- {
- this.r = r;
- }
- @Override
- public void run() {
- while(true)
- {
- r.getInfo();
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/261220138265.html
来源: http://www.codesnippet.cn/detail/261220138265.html