Synchronize對String加鎖解決
阿新 • • 發佈:2019-01-25
Synchronize
儘量,不要使用String常量加鎖
會出現死迴圈問題
new String
可以使用new String加鎖
package com.bjsxt.base.sync006;
/**
* synchronized程式碼塊對字串的鎖,注意String常量池的快取功能
*
*/
public class StringLock {
public void method() {
// new String("字串常量")
synchronized (new String("字串常量")) {
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() {
@Override
public void run() {
stringLock.method();
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
stringLock.method();
}
}, "t2");
t1.start();
t2.start();
}
}
執行