美文网首页
Synchronized 详解

Synchronized 详解

作者: 福later | 来源:发表于2018-07-02 16:06 被阅读0次

    转载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();
        }
    
    }
    

    }

    相关文章

      网友评论

          本文标题:Synchronized 详解

          本文链接:https://www.haomeiwen.com/subject/rpsluftx.html