• 2.2.4一半异步,一半同步


    本例说明:不在同步代码块的是异步执行,在同步代码块时同步的

    package com.cky.bean;
    
    /**
     * Created by chenkaiyang on 2017/12/6.
     */
    public class ObjectService {
        public void serviceMethodA(){
            for (int i = 0; i < 100; i++) {
                System.out.println("no同步"+ Thread.currentThread().getName() +" i="+(i+1));
            }
            System.out.println("");
            synchronized (this) {
                for (int i = 0; i < 100; i++) {
                    System.out.println("同步"+ Thread.currentThread().getName() +" i="+(i+1));
                }
            }
    
        }
    
    }
    package com.cky.thread;
    
    import com.cky.bean.ObjectService;
    
    /**
     * Created by chenkaiyang on 2017/12/5.
     */
    public class ThreadA extends Thread{
        private ObjectService service;
        public ThreadA(ObjectService service) {
            super();
            this.service = service;
        }
    
        @Override
        public void run() {
            super.run();
            service.serviceMethodA();
        }
    }
    package com.cky.thread;
    
    import com.cky.bean.ObjectService;
    
    /**
     * Created by chenkaiyang on 2017/12/5.
     */
    public class ThreadB extends  Thread{
        private ObjectService service;
        public ThreadB(ObjectService service) {
            super();
            this.service = service;
        }
    
        @Override
        public void run() {
            super.run();
            service.serviceMethodA();
        }
    }
    package com.cky.test;
    
    import com.cky.bean.ObjectService;
    import com.cky.thread.ThreadA;
    import com.cky.thread.ThreadB;
    
    /**
     * Created by chenkaiyang on 2017/12/6.
     */
    public class Test2 {
        public static void main(String[] args) {
            ObjectService objectService = new ObjectService();
            ThreadA a = new ThreadA(objectService);
            a.setName("a");
            ThreadB b = new ThreadB(objectService);
            b.setName("b");
            a.start();
            b.start();
    
        }
    }
    no同步a i=1
    no同步b i=1
    no同步b i=2
    no同步b i=3
    no同步b i=4
    no同步b i=5
    no同步b i=6
    no同步b i=7
    no同步b i=8
    同步b i=1
    同步b i=2
    同步b i=3
    同步b i=4
    同步b i=5
    同步b i=6
    同步b i=7
    同步b i=8
    同步b i=9
    同步b i=10

    结果可知:同步代码块的代码是排队执行的,而非同步代码块是异步执行的。

  • 相关阅读:
    python xlrd和xlwtxlutils包的使用
    python中的re模块和正则表达式基础
    linux定时任务crontab
    分析nginx access log日志的命令
    Git SSH Key 生成步骤
    mysql分表的3种方法
    memcached全面剖析–5. memcached的应用和兼容程序
    memcached全面剖析–4. memcached的分布式算法
    memcached全面剖析–3. memcached的删除机制和发展方向
    memcached全面剖析–2. 理解memcached的内存存储
  • 原文地址:https://www.cnblogs.com/edison20161121/p/7989482.html
Copyright © 2020-2023  润新知