继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Notifyl学习笔记

html5零基础入门学习
关注TA
已关注
手记 246
粉丝 81
获赞 518

/**     * @param args     * 等待唤醒机制     */    public static void main(String[] args) {        final Printer p = new Printer();        new Thread() {            public void run() {                while(true) {                    try {                        p.print1();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }        }.start();        new Thread() {            public void run() {                while(true) {                    try {                        p.print2();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }        }.start();    }}//等待唤醒机制class Printer {    private int flag = 1;    public void print1() throws InterruptedException {                                  synchronized(this) {            if(flag != 1) {                this.wait();                    //当前线程等待            }            System.out.print("白");            System.out.print("日");            System.out.print("一");            System.out.print("山");            System.out.print("过");            System.out.print("\r\n");            flag = 2;            this.notify();                      //随机唤醒单个等待的线程        }    }    public void print2() throws InterruptedException {        synchronized(this) {            if(flag != 2) {                this.wait();            }            System.out.print("黄");            System.out.print("河");            System.out.print("入");            System.out.print("海");            System.out.print("流");            System.out.print("\r\n");            flag = 1;            this.notify();        }    }

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP