zoukankan      html  css  js  c++  java
  • 静态方法和非静态方法是否存在竞争关系

    问题一:静态与非静态方法是否存在竟态
    静态同步方法与非静态同步方法存不存在竟态条件,通俗地说就是分别调用静态同步方法和非静态同步方法的两个线程会不会同步?

    不会,静态方法请求的是类的同步监视器,而非静态方法请求的是实例的monitor。

    以下是测试代码:

    public class TestSynchronized {
    
    static final int COUNT = 1000;
    
    static synchronized void staticSyn() {
    for (int i = 0; i < COUNT; i++) {
    System.out.println("staticSyn " + i);
    }
    }
    
    synchronized void instanceSyn() {
    for (int i = 0; i < COUNT; i++) {
    System.out.println("instanceSyn " + i);
    }
    }
    
    void blockInstance() {
    synchronized (this) {
    for (int i = 0; i < COUNT; i++) {
    System.out.println("blockInstance " + i);
    }
    }
    }
    
    void blockClass() {
    synchronized (this.getClass()) {
    for (int i = 0; i < COUNT; i++) {
    System.out.println("blockClass " + i);
    }
    }
    }
    
    }


    测试:

    public static void main(String[] args) {
    new Thread(new Runnable() {
    
    @Override
    public void run() {
    TestSynchronized.staticSyn();
    }
    }).start();
    
    new Thread(new Runnable() {
    
    @Override
    public void run() {
    new TestSynchronized().instanceSyn();
    }
    }).start();
    
    }

    部分输出结果:

    staticSyn 953
    staticSyn 954
    staticSyn 955
    staticSyn 956
    staticSyn 957
    staticSyn 958
    staticSyn 959
    instanceSyn 671
    instanceSyn 672
    instanceSyn 673
    instanceSyn 674
    staticSyn 960
    staticSyn 961
    staticSyn 962
    staticSyn 963



    问题二:synchronized (this.getClass())与静态同步方法存不存在竟态条件
    存在,二者都是请求类的同步监视器。

    测试代码:

    public static void main(String[] args) {
    new Thread(new Runnable() {
    
    @Override
    public void run() {
    TestSynchronized.staticSyn();
    }
    }).start();
    
    new Thread(new Runnable() {
    
    @Override
    public void run() {
    new TestSynchronized().blockClass();
    }
    }).start();
    
    }


    输出结果:

    staticSyn 994
    staticSyn 995
    staticSyn 996
    staticSyn 997
    staticSyn 998
    staticSyn 999
    blockClass 0
    blockClass 1
    blockClass 2
    blockClass 3
    blockClass 4
    blockClass 5
    blockClass 6
    blockClass 7
    blockClass 8



    总结
    1、静态同步方法与非静态同步方法不存在竟态条件,前者请求类的同步监视器,后者请求的实例的同步监视器;
    2、synchronized (this.getClass())与静态同步方法存在竟态条件,二者均请求类的同步监视器。

    3、静态同步方法是锁的class文件,非静态同步方法锁的是this

  • 相关阅读:
    报到开博随笔
    为Windows2008升级系统补丁
    String:本质上是字符数组
    为Windows2008服务器安装.NET Framework 3.0
    设计ShartPoint的组织结构和成员
    中文:一个面向对象的自然语言
    从一个帖子看部分大学生的学习心态
    Enum:枚举
    Array:一组数据的有序集合
    部署SQL Server2008企业版
  • 原文地址:https://www.cnblogs.com/xhlwjy/p/11720138.html
Copyright © 2011-2022 走看看