Java多線程鎖對象的改變
用lock獲取鎖對象,當(dāng)lock被修改以后,會產(chǎn)生是一把新的鎖,另一個(gè)線程獲取鎖對象時(shí)會獲取這把新的鎖,導(dǎo)致線程異步執(zhí)行.
public class ChangeLock {
private String lock = "lock";
private void method(){
System.out.println(Thread.currentThread().getName() + "開始"+"獲取鎖對象"+lock);
synchronized (lock) {
try {
System.out.println("當(dāng)前線程 : " + Thread.currentThread().getName() + "獲得了"+"鎖對象"+lock);
lock = "change lock";
Thread.sleep(2000);
System.out.println("當(dāng)前線程 : " + Thread.currentThread().getName() + "結(jié)束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
final ChangeLock changeLock = new ChangeLock();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
changeLock.method();
}
},"t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
changeLock.method();
}
},"t2");
t1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
log信息
//正常試驗(yàn)結(jié)果
t1開始獲取鎖對象lock
當(dāng)前線程 : t1獲得了鎖對象lock
t2開始獲取鎖對象change lock
當(dāng)前線程 : t2獲得了鎖對象change lock
當(dāng)前線程 : t1結(jié)束
當(dāng)前線程 : t2結(jié)束
//sleep注銷了的log信息
t1開始獲取鎖對象lock
t2開始獲取鎖對象lock
當(dāng)前線程 : t1獲得了鎖對象lock
當(dāng)前線程 : t1結(jié)束
當(dāng)前線程 : t2獲得了鎖對象change lock
當(dāng)前線程 : t2結(jié)束