• 静态同步synchronized方法和synchronized(class)代码块


    关键字synchronized还可以应用在static静态方法上,如果这样写,那是对当前的*.java文件对应的Class类进行持锁。

    package synStaticMethod;
    
    /**
     * Created by Administrator on 2017/1/22 0022.
     */
    public class Service {
        synchronized public  static  void printA(){
            try{
            System.out.println("线程名称为:"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"进入printA");
                Thread.sleep(3000);
                System.out.println("线程名称为:"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"离开printA");
    
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        synchronized public static  void printB(){
            System.out.println("线程名称为:"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"进入printB");
            System.out.println("线程名称为:"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"离开printB");
    
        }
    }
    package synStaticMethod;
    
    
    /**
     * Created by Administrator on 2017/1/22 0022.
     */
    public class ThreadA extends Thread{
        public void run(){
            Service.printA();
        }
    }
    package synStaticMethod;
    
    /**
     * Created by Administrator on 2017/1/22 0022.
     */
    public class ThreadB extends Thread {
        public void run(){
            Service.printB();
        }
    }
    package synStaticMethod;
    
    /**
     * Created by Administrator on 2017/1/22 0022.
     */
    public class Run {
        public static  void main(String[]args){
            ThreadA threadA =  new ThreadA();
            threadA.setName("A");
            threadA.start();
            ThreadB threadB = new ThreadB();
            threadB.setName("B");
            threadB.start();
        }
    }
    线程名称为:A在1485063366543进入printA
    线程名称为:A在1485063369543离开printA
    线程名称为:B在1485063369543进入printB
    线程名称为:B在1485063369543离开printB

    从结果来看,是同步的效果,和将synchronized关键字加到非静态方法上使用的效果是一样的,其实synchronized关键字加到static静态方法上是给Class类上锁,而synchronized关键字加到非static静态方法上是给对象加锁。

  • 相关阅读:
    routine的加载
    Forms Authentication and Role based Authorization: A Quicker, Simpler, and Correct Approach
    How does Request.IsAuthenticated work?
    细说ASP.NET Forms身份认证
    IIS URL Rewriting and ASP.NET Routing
    Razor syntax reference for ASP.NET Core
    win10 合并磁盘 disk Acronis Disk Director
    bad object refs/remotes/origin/HEAD
    https://www.atlassian.com/git/tutorials/git-gc
    c++ 中文字符串处理方法
  • 原文地址:https://www.cnblogs.com/dream-to-pku/p/6340250.html
Copyright © 2020-2023  润新知