黑马程序员技术交流社区

标题: 两个线程 [打印本页]

作者: 何亚辉    时间: 2016-5-17 22:33
标题: 两个线程
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;
                }
                        }

                }
                }
               
        }



}


作者: 何亚辉    时间: 2016-5-17 22:35
http://bbs.itheima.com/forum.php?mod=attachment&aid=MTEwMDk3fDY0YTJlNTUyODkzYTVkZjgzZTFhNGZjN2I2YjgzOTM3fDE3NjcwMDIxMzg%3D&request=yes&_f=.png

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

9%~`2()$C)SJ{52EQSM1H`V.png





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2