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
總結
以上是生活随笔為你收集整理的synchronized(九)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设计模式学习总结(一)——设计原则与UM
- 下一篇: java输入最大10位数,倒数输出(很鸡