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

     java锁实现原理:

    http://blog.csdn.net/endlu/article/details/51249156

    The synchronized keyword can be used to mark four different types of blocks:

    1. Instance methods
    2. Static methods
    3. Code blocks inside instance methods
    4. Code blocks inside static methods

    Instance methods & Code blocks inside instance methods

    Java实例方法同步是同步在拥有该方法的对象上

    同步构造器中用括号括起来的对象叫做监视器对象

    public class SyncBlockTest {
    
        public static void main(String[] args) {
            ExecutorService es = Executors.newFixedThreadPool(2);
            final MySyncBlockClass syncBlockClass = new MySyncBlockClass();
            es.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        syncBlockClass.mehtod1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            es.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        syncBlockClass.mehtod2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            es.shutdown();
        }
    
    }
    
    class MySyncBlockClass {
    
        public synchronized void mehtod1() throws InterruptedException {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(System.currentTimeMillis() + ":method1 run.");
        }
    
        public synchronized void mehtod2() throws InterruptedException {
            TimeUnit.SECONDS.sleep(4);
            System.out.println(System.currentTimeMillis() + ":method2 run.");
        }
    }
    
    // method1较method2延迟了2000ms
    // 1479350064132:method2 run. 
    // 1479350066132:method1 run.
    实例方法同步
    /**
         * method1 与method2等效
         * 同步构造器中用括号括起来的对象叫做监视器对象
         * 
         * @throws InterruptedException
         */
        public synchronized void mehtod1() throws InterruptedException {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(System.currentTimeMillis() + ":method1 run.");
        }
    
        public synchronized void mehtod2() throws InterruptedException {
            synchronized (this) {
                TimeUnit.SECONDS.sleep(4);
                System.out.println(System.currentTimeMillis() + ":method2 run.");
            }
        }
    实例方法中的同步块

    Static methods & Code blocks inside static methods

    静态方法的同步是指同步在该方法所在的类对象上。因为在Java虚拟机中一个类只能对应一个类对象,所以同时只允许一个线程执行同一个类中的静态同步方法。

    public class SyncBlockTest {
    
        public static void main(String[] args) {
            ExecutorService es = Executors.newFixedThreadPool(2);
            final MySyncBlockClass syncBlockClass1 = new MySyncBlockClass();
            final MySyncBlockClass syncBlockClass2 = new MySyncBlockClass();
            es.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        syncBlockClass1.mehtod1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            es.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        syncBlockClass2.mehtod2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            es.shutdown();
        }
    
    }
    
    class MySyncBlockClass {
    
        public static synchronized void mehtod1() throws InterruptedException {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(System.currentTimeMillis() + ":method1 run.");
        }
    
        public static synchronized void mehtod2() throws InterruptedException {
            TimeUnit.SECONDS.sleep(4);
            System.out.println(System.currentTimeMillis() + ":method2 run.");
        }
    }
    
    // method1较method2延迟了3000ms
    // 1479358310630:method1 run.
    // 1479358314631:method2 run.
    静态方法同步
    /**
         * method1 与method2等效
         * 静态方法中的同步块
         *
         * @throws InterruptedException
         */
        public static synchronized void mehtod1() throws InterruptedException {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(System.currentTimeMillis() + ":method1 run.");
        }
    
        public static synchronized void mehtod2() throws InterruptedException {
            synchronized (MySyncBlockClass.class) {
                TimeUnit.SECONDS.sleep(4);
                System.out.println(System.currentTimeMillis() + ":method2 run.");
            }
        }
    静态方法中的同步块

    示例:

    以下代码对应的Block关系如下:

    synchronized(class)与 static synchronized 等效
    public class SyncMethod2 {
        private int value = 0;
        private final Object mutex = new Object();
    
        public synchronized int incAndGet0() {
            try {
                TimeUnit.SECONDS.sleep(4);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("static synchronized void incAndGet0");
            return ++value;
        }
    
        public int incAndGet1() {
            synchronized(this){
                try {
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("static synchronized void incAndGet1");
                return ++value;
            }
        }
    
        public int incAndGet2() {
            synchronized(SyncMethod.class){
                ++value;
                try {
                    TimeUnit.SECONDS.sleep(4);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("static synchronized void incAndGet4");
            }
            return 0;
        }
    
        public int incAndGet3() {
            synchronized(mutex){
                return ++value;
            }
        }
    
        public static synchronized void incAndGet4() {
            try {
                TimeUnit.SECONDS.sleep(4);
                System.out.println("static synchronized void incAndGet4");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    各种同步场景
  • 相关阅读:
    区块链解读
    如何在ASP.NET Core项目启动时执行异步定时任务
    深入理解ASP.NET Core中的Program类和Startup类
    VS 2017 .Net Core Error : 项目文件不完整,缺少预期导入。
    dotnet不是内部或外部的命令,也不是可运行的程序或批处理文件
    win10系统卸载matlab时出现exeption calling main怎么解决?
    解决mui错误:Unable to preventDefault inside passive event listener due to target being treated as passive.
    类型"*.Properties.Resources" 没有名为"*"的属性
    C#生成唯一不重复订单号帮助类
    Day16.参数传递(token传递,接口关联等)
  • 原文地址:https://www.cnblogs.com/binnzhao/p/6073312.html
Copyright © 2011-2022 走看看