synchronized(六)

package com.bjsxt.base.sync006;
/**
* 锁对象的改变问题
* @author alienware
*
*/
public class ChangeLock {

private String lock = "lock";

private void method(){
synchronized (lock) {
try {
System.out.println("当前线程 : " + Thread.currentThread().getName() + "开始");
lock = "change lock";
Thread.sleep(2000);
System.out.println("当前线程 : " + Thread.currentThread().getName() + "结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {

final ChangeLock changeLock = new ChangeLock();
Thread t1 = new Thread(new Runnable() {

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

public void run() {
changeLock.method();
}
},"t2");
t1.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}

}

运行结果:

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

去掉lock = "change lock";运行结果:

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

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