交替打印FooBar

交替打印FooBar

交替打印FooBar_第1张图片

class FooBar {
    private int n;

    private int i = 0;

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        synchronized (this){
            while(i < n * 2){
                if(i % 2 == 0){
                    printFoo.run();
                    i += 1;
                    notifyAll();
                }else {
                    wait();
                }
            }
        }

    }

    public void bar(Runnable printBar) throws InterruptedException {

        synchronized (this){
            while(i < n * 2){
                if(i % 2 == 1){
                    printBar.run();
                    i += 1;
                    notifyAll();
                }else {
                    wait();
                }
            }
        }
    }
}

交替打印FooBar_第2张图片

你可能感兴趣的:(多线程,leetecode,交替打印FooBar)