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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© xianghui0521 中级黑马   /  2016-9-28 23:08  /  678 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

用两个线程 输出  打印结果如  12A34B56C........52Z (唤醒)











final MyThread mt = new MyThread();
                // 创建线程并在run()方法中调用print1()
                new Thread() {
                        public void run() {
                                try {
                                        mt.print1();
                                } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                        }
                }.start();
                // //创建线程并在run()方法中调用print1()
                new Thread() {
                        public void run() {
                                try {
                                        mt.print2();
                                } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                        }
                }.start();
        }
}

class MyThread {
        // 定义静态变量
        private static int sum = 1;
        private static char c = 'A';
        private static int flag = 1;

        public void print1() throws InterruptedException {
                // 创建循环
                while (sum <= 52) {
                        // 创建锁
                        synchronized (this) {
                                // 定义线程间的通信
                                if (flag != 1)
                                        this.wait();
                                // 内部循环每次调通该方法输出两次
                                for (int i = 1; i <= 2; i++) {
                                        System.out.print(sum);
                                        sum++;
                                }
                                flag = 2;
                                this.notify();
                        }
                }
        }

        public void print2() throws InterruptedException {
                // 创键循环
                while (c <= 'Z') {
                        // 创建锁
                        synchronized (this) {
                                // 创建线程间的通信
                                if (flag != 2)
                                        this.wait();
                                System.out.print(c);
                                c = (char) (c + 1);
                                flag = 1;
                                this.notify();
                        }
                }
        }
}

3 个回复

倒序浏览
还不会 哦
回复 使用道具 举报
学习了1111
回复 使用道具 举报

这个  老师就大楷讲了一下. 结果就考了...  也没给什么练习题做过
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马