zoukankan      html  css  js  c++  java
  • 同步代码块

    什么情况下需要同步

    • 当多线程并发, 有多段代码同时执行时, 我们希望某一段代码执行的过程中CPU不要切换到其他线程工作. 这时就需要同步.
    • 如果两段代码是同步的, 那么同一时间只能执行一段, 在一段代码没执行结束之前, 不会执行另外一段代码.

    作用: 保证了数据的安全性


    弊端: 程序的运行效率低


    格式:

    synchronized(对象) {
    
        要被同步的代码 ;
    
    }
    

    同步代码块 , 同步方法 , 静态同步方法的锁对象问题:

    同步代码块的锁对象是任意对象

    同步方法的锁对象为this

    静态同步方法的锁对象是该类的字节码文件对象

    class Printer {
        Demo d = new Demo();
        public static void print1() {
            synchronized(d){                //锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象
                System.out.print("我");
                System.out.print("爱");
                System.out.print("编");
                System.out.print("程");
                System.out.print("!");
                System.out.print("
    ");
            }
        }
    
        public static void print2() {   
            synchronized(d){    
                System.out.print("我");
                System.out.print("爱");
                System.out.print("中");
                System.out.print("国");
                System.out.print("
    ");
            }
        }
    }
    
  • 相关阅读:
    Windows10 搭建 ElasticSearch 集群服务
    python开发目录
    nohup命令使用
    shell脚本概述
    关于ELK
    keepalived+DR
    shell脚本中awk的用法
    shell脚本中sed的用法
    shell脚本中grep的用法
    shell检测入侵与邮件报警
  • 原文地址:https://www.cnblogs.com/loaderman/p/6411163.html
Copyright © 2011-2022 走看看