Synchronized 详解

2018-07-02  本文已影响0人  福later

转载https://www.jianshu.com/p/29854dc7bd86
面试题:主线程执行10次,子线程接着执行2次,主线程再执行10次,子线程接着执行2次,如此循环此行50次。
分析,两个线程串行交替执行;完整源码如下

public class InterViewOne {

public static void main(String[] args) {
    InterViewOne one = new InterViewOne();
    final Business business = one.init();
    new Thread(new Runnable() {

        @Override
        public void run() {
            for (int j = 0; j < 50; j++) {
                business.sub(j);
            }
        }
    }).start();

    for (int j = 0; j < 50; j++) {
        business.main(j);
    }
}

public Business init() {
    return new Business();

}

class Business {
    private boolean isShouldSub = true;

    public synchronized void sub(int i) {
        if (!isShouldSub) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        for (int j = 1; j <= 2; j++) {
            System.out.println("sub thread sequeue of " + j + ",loop of "
                    + i);
        }
        isShouldSub = false;
        this.notify();

    }

    public synchronized void main(int i) {
        if (isShouldSub) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        for (int j = 1; j <= 10; j++) {
            System.out.println("main thread sequeue of" + j + ",loop of "
                    + i);
        }
        isShouldSub = true;
        this.notify();
    }

}

}

上一篇 下一篇

猜你喜欢

热点阅读