zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    #负分小组WEEK1#本周工作小结+下周计划
    #负分小组WEEK1#软件开发之路——需求获取与相关建模
    #负分小组WEEK1#第一次会议纪要
    #负分小组WEEK1#软件开发之路——准备阶段
    #负分小组WEEK1#确定项目——“宝宝睡吧!”儿童睡前服务服务软件+计划分工
    p6spy sql 执行记录
    apache common-lang3 工具类
    根据 ip 定位
    springcloud 与 spring boot 版本对应关系
    PowerDesign 基于mysql 数据库建模
  • 原文地址:https://www.cnblogs.com/edison20161121/p/7989482.html
Copyright © 2011-2022 走看看