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

© 何亚辉 中级黑马   /  2016-5-17 22:33  /  335 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class Play8 {
        public static void main(String[] args){
                Array a = new Array(true);
                Array a1 = new Array(false);
                new Thread(a,"1号线程").start();
                new Thread(a1, "2号线程").start();
       
        }
}

class Array implements Runnable {
        static int inpros;
        static int outpros;
        static int[] arr = new int[10];
        static Object o1 = new Object();
        boolean flag;

        public Array(boolean flag){
        this.flag = flag;
        }

        public void run(){
                if (flag) {
                                synchronized(o1){
                        while (inpros<=9) {
                                try {
                                        Thread.sleep(200);
                                }
                                catch (InterruptedException e) {
                                       
                                }
                        arr[inpros]= (int)(100*Math.random())+1;
                        System.out.println(Thread.currentThread().getName() +"正在往数组里投入"+ arr[inpros++]);
                if (inpros==10) {
                        inpros =0;
                        break;
                }
                        }
                }
                }else {
                synchronized(o1){
                        while (true) {
                                try {
                                        Thread.sleep(200);
                                }
                                catch (InterruptedException e) {
                                        e.printStackTrace();
                                }
                                                System.out.println(Thread.currentThread().getName() +"正在往数组里拿出"+ arr[outpros++]);
                if (outpros ==10) {
                        outpros =0;
                        break;
                }
                        }

                }
                }
               
        }



}

1 个回复

倒序浏览
http://bbs.itheima.com/forum.php?mod=attachment&aid=MTEwMDk3fGQ4M2M3NzlmN2Q2ZTIyMTkxMTgxMmJiOGVlNzYxZDBifDE3NjQ5ODYwNTc%3D&request=yes&_f=.png

9%~`2()$C)SJ{52EQSM1H`V.png (19.12 KB, 下载次数: 9)

9%~`2()$C)SJ{52EQSM1H`V.png
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马