String字串作為鎖的影響
阿新 • • 發佈:2019-01-28
我們都知道Java中String 常量池的功能,先看下面的程式碼:
public class Test184 {
static String a = "a";
static String b = "a";
public static void main(String[] args) {
System.out.println(a==b);
}
}
由上面可知:雖然兩個變數,都是指向同一個字串地址。
下面我們來看,synchronized(String)同步程式碼塊與String聯合使用帶來的問題。
public class Test183Service {
public static void show(String content) {
synchronized (content) {
while(true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
MyTaskThread mtt = new MyTaskThread();
Thread t = new Thread(mtt);
Thread t1 = new Thread(mtt);
t.start();
t1.start();
}
}
class MyTaskThread implements Runnable{
Test183Service ts = new Test183Service();
@Override
public void run() {
// TODO Auto-generated method stub
ts.show("aa");
}
}
執行的結果:一個執行緒執行之後,另外一個執行緒就不會獲取執行緒執行機會。原因就是String常量池帶來的問題,兩個字元實則是一個物件,show方法鎖持有的是相同的鎖,因此在大多數情況下,同步synchronized程式碼塊都不使用String作為鎖物件,而改用其他,比如例項一個Object物件。