synchronized(九)

在Java中是有常量池缓存的功能的,就是说如果我先声明了一个String str1 = “a”; 再声明一个一样的字符串的时候,取值是从原地址去取的,也就是说是同一个对象。这也就导致了在锁字符串对象的时候,可以会取得意料之外的结果(字符串一样会取得相同锁)。

package com.bjsxt.base.sync006;
/**
* synchronized代码块对字符串的锁,注意String常量池的缓存功能,
* @author alienware
*
*/
public class StringLock {

public void method() {
//new String("字符串常量")
synchronized ("字符串常量") {
try {
while(true){
System.out.println("当前线程 : " + Thread.currentThread().getName() + "开始");
Thread.sleep(1000);
System.out.println("当前线程 : " + Thread.currentThread().getName() + "结束");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
final StringLock stringLock = new StringLock();
Thread t1 = new Thread(new Runnable() {

public void run() {
stringLock.method();
}
},"t1");
Thread t2 = new Thread(new Runnable() {

public void run() {
stringLock.method();
}
},"t2");

t1.start();
t2.start();
}
}

运行结果:

当前线程 : t1开始
当前线程 : t1结束
当前线程 : t1开始
当前线程 : t1结束
当前线程 : t1开始

。。。。。。。。

改为synchronized (new String("字符串常量"))之后,运行结果:

当前线程 : t1开始
当前线程 : t2开始
当前线程 : t2结束
当前线程 : t1结束
当前线程 : t1开始
当前线程 : t2开始

。。。。。。。。

原文地址:https://www.cnblogs.com/tsdblogs/p/8761030.html