小编典典

Locking on Strings

java

2 Questions:

  1. str field is shared between two instance of A type [line 2]
  2. What’s implications according to following code ?

class A implements Runnable {
    String str = "hello"; // line 2.

    public void run(){
        Synchronized(str){
            System.out.println(str+" "+Thread.currentThread().getName());
            Thread.sleep(100);
            System.out.println(str+" "+Thread.currentThread().getName());
            //anything
        }
    }

    public void static main(String[] args){  
        Thread one = new Thread(new A(),"one").start();  
        Thread two = new Thread(new A(),"two").start();  
    }
}

阅读 191

收藏
2020-11-23

共1个答案

小编典典

该字段本身不在两个实例之间共享。它们是不同的
领域。但是,它们以相同的值开始,因为要插入字符串文字

这意味着,当该synchronized块在一个
线程中获取字符串的监视器时,它将阻止另一线程获取同一监视器。这是
理解的重要synchronized区块获取锁
与相关监控值字段的-它并不重要
,有涉及到两个不同的领域。

道德:不要同步字符串,尤其是文字。文字
特别糟糕,因为在这种情况下,您可能会拥有另一个类,其
代码与相同A,并且还会尝试使用相同的
监视器进行同步。

2020-11-23