首页 / Java求职圈
Java求职圈
本圈子供Java开发工程师方向求职者使用,用于交流求职招聘消息,求职招聘进度,笔试面试offer信息等内容
圈主: 牛客0063号 创建于2019-08-05
发动态
此刻你想和大家分享什么
动态 圈友
今天 10:06
武汉大学 C++
多线程问题
问问大佬们(1)class ZeroEvenOdd {    private int n;    ReentrantLock lock = new ReentrantLock(true);    private int x = 1;    private boolean isZero = true;    private Condition condition = lock.newCondition();    public ZeroEvenOdd(int n) {                this.n = n;    }    // printNumber.accept(x) outputs "x", where x is an integer.    public void zero(IntConsumer printNumber) throws InterruptedException {        while(x <= n){                    lock.lock();        if(isZero&&x <= n){            printNumber.accept(0);            isZero = false;            condition.signalAll();        }else{            condition.await();        }        lock.unlock();        }    }    public void even(IntConsumer printNumber) throws InterruptedException {        while(x <= n){        lock.lock();        if(!isZero && x%2 == 0){            printNumber.accept(x);            x++;            isZero = true;            condition.signalAll();        }else{            condition.await();        }        lock.unlock();        }           }    public void odd(IntConsumer printNumber) throws InterruptedException {        while(x <= n){        lock.lock();        if(!isZero && x%2 == 1){            printNumber.accept(x);            x++;            isZero = true;            condition.signalAll();        }else{            condition.await();        }        lock.unlock();        }        }}(2)class ZeroEvenOdd {    private final int n;    private int x = 1;    // true: 打印0  false: 不打印0    private boolean isZero = true;    public ZeroEvenOdd(int n) {        this.n = n;    }    public void zero(IntConsumer printNumber) throws InterruptedException {        while (x <= n) {            synchronized (this) {                if (isZero) {                    printNumber.accept(0);                    isZero = false;                    this.notifyAll();                } else {                    this.wait();                }            }        }    }    public void even(IntConsumer printNumber) throws InterruptedException {        while (x <= n) {            synchronized (this) {                if (x % 2 == 0 && !isZero) {                    printNumber.accept(x);                    isZero = true;                    x++;                    this.notifyAll();                } else {                    this.wait();                }            }        }    }    public void odd(IntConsumer printNumber) throws InterruptedException {        while (x <= n) {            synchronized (this) {                if (x % 2 != 0 && !isZero) {                    printNumber.accept(x);                    isZero = true;                    x++;                    this.notifyAll();                } else {                    this.wait();                }            }        }    }}为什么(1)代码最后可能多输出一个0。(2)代码不会
点赞 评论 收藏
分享
玩命加载中
牛客网
牛客企业服务