A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© chenyanwei6 中级黑马   /  2016-12-23 21:19  /  832 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package com.heima.code;
/*
本程序的需求:
读取一条,写出一条
分析:
1.在读取时,首先判断里面是否能写入,也就是标记flag,若为flase,就读取,在读取完之前,唤醒写出线程,若为true,就不读取;
2.在写出时,要在写完之前,唤醒读取线程,因为此时的读取线程正在等待。
3.就这样的交替进行读取和写出操作。


本程序是等待唤醒机制:
* */

class ResourceDemo02{
        String name;
        String sex;
        boolean flag = false;
}
class InputDemo02 implements Runnable{
    private ResourceDemo02 resd02;
        InputDemo02(ResourceDemo02 resd02){
                this.resd02 = resd02;
    }
        @Override
        public void run() {
        show();
        }
        public void show(){
                int x=0;
                while(true){
                synchronized (resd02) {
                if(resd02.flag){
                                try {
                                        resd02.wait();
                                } catch (Exception e) {
                                       
                                }
                        if(x==0){                       
                                resd02.name = "小红";
                                resd02.sex = "..................woman";               
                        }else{       
                                 resd02.name = "Franke";
                                resd02.sex = "man";               
                        }
                        x=(x+1)%2;
                }          
                    resd02.flag = true;
                        resd02.notify();
        }       
           }
        }
}
class OutputDemo02 implements Runnable{
        private ResourceDemo02 resd02;

    OutputDemo02(ResourceDemo02 resd02){
            this.resd02 = resd02;
    }
        @Override
        public void run() {
                while(true){                       
                        synchronized (resd02) {                               
                                if(!resd02.flag)
                                        try {
                                                resd02.wait();//等待
                                        } catch (Exception e) {}
                                System.out.println(resd02.name+"...."+resd02.sex);
                                resd02.flag = false;
                                resd02.notify();//唤醒
                        }
            }
        }
}
public class InputOutputThreadDemo02 {

        public static void main(String[] args) {
       ResourceDemo02 resd02 = new ResourceDemo02();
      
       InputDemo02 inPut = new InputDemo02(resd02);
       OutputDemo02 outPut = new OutputDemo02(resd02);
      
       Thread tInput = new Thread(inPut);
       Thread tOutput = new Thread(outPut);
      
       tInput.start();
       tOutput.start();
      
        }

}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马