码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-24 13:26:40      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:color   通信技术   block   generated   线程同步   cas   dex   cat   for   

子线程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();
        }
        
    }

}

 

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

标签:color   通信技术   block   generated   线程同步   cas   dex   cat   for   

原文地址:http://www.cnblogs.com/404-not-found/p/7228084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!