(黑马Java多线程与并发库高级应用)04 传统线程同步通信技术

子线程10次,然后主线程100次,然后子线程10次,然后主线程100次。循环50次

package cn.itcast.heima2;

public class TraditionalThreadComunication {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Business business = new TraditionalThreadComunication().new Business();

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                for (int i = 0; i < 50; i++) {
                    business.sub(i);
                }
            }

        }).start();
        

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

    class Business {
        
        private boolean bShouldSub=true;
        
        public synchronized void sub(int i) {
            if(!bShouldSub){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            for (int j = 0; j < 10; j++) {
                System.out.println("sub thread sequence:" + j + " loop of " + i);
            }
            bShouldSub=false;
            this.notify();
            
        }

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

}

 

posted @ 2017-07-24 11:34  z_dominic  阅读(139)  评论(0编辑  收藏  举报