【问题标题】:Class level lock for static variables in javajava中静态变量的类级锁
【发布时间】:2015-10-23 11:35:23
【问题描述】:

如果我在我的 java 类 X 中不使用任何 setter/getter。当线程 A 具有我的类 X 的类级别锁定时。另一个线程 B 可以直接更改我的静态变量吗??

public class X {

    Integer static_variable = 10;

    public static void doNothing {
        /* Do Nothing */
    }

}

假设线程 A 现在有类级别的锁。我可以从另一个线程 B 执行 X.static_variable = 11 吗?

我正在编写一个代码以在 java 中出现死锁。

公共类 A 实现 Runnable {

    public static Integer as = 5;
    static A a = new A();
    static B b = new B();

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here

    Thread thread1 = new Thread(a);
    Thread thread2 = new Thread(b);
    thread1.setName("First");
    thread2.setName("Second");
    thread1.start();
    thread2.start();
}


public void run() {    
    runme();

}

public static synchronized void runme() {
    try {
    System.out.println(Thread.currentThread().getName() + " has object a's key and waiting");
    Thread.sleep(1000);
    System.out.println(Thread.currentThread().getName() + " Woke up from sleep"); 
    System.out.println(Thread.currentThread().getName() + " wants b's Key"); 

    B.bs = 10;
    System.out.println(Thread.currentThread().getName() + " over"); 

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}

公共类 B 实现 Runnable {

public static Integer bs = 6;

public void run() {
    runme();
}

public static synchronized void runme() {
    try {
        System.out.println(Thread.currentThread().getName() + " has object b's key and waiting");
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + " Woke up from sleep");
        System.out.println(Thread.currentThread().getName() + " wants a's Key");

        A.as = 10;
        System.out.println(Thread.currentThread().getName() + " over");

    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

}

但得到以下结果:

Second 有对象 b 的键并等待 首先有对象a的键并等待 第一次从睡梦中醒来 第二次从睡梦中醒来 二要a's Key 第二次结束 首先要b的钥匙 首当其冲

即使另一个线程持有 A 类的类级锁,第二个线程也明显在编辑 A 类的静态变量

【问题讨论】:

    标签: java multithreading locks


    【解决方案1】:

    是的,你可以。除非您在变量更改代码周围有 synchronized 块。如果您不使用同步,其他线程不必在更改其static_variable之前获取X.class的监视器。

    将字段设为private,并添加一个setter,使其同步,然后当另一个线程持有X.class的锁时,您将无法更改该字段 p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      相关资源
      最近更新 更多