不可以更改对象锁的引用
import java.util.logging.Level;import java.util.logging.Logger;/** * * @author max * 可以修改锁的内容,但不能修改锁的引用 */public class TestNotify{ static Boolean lock = true;// static A lock = new A(1); static Boolean condition = true; public static void main(String[] args) throws Exception{ new TestThread().start(); new TestThread().start(); Thread.sleep(1000); System.out.println("Doing something"); synchronized(lock){// Boolean b = lock; //这样就可以了// lock.setA(0); //语句1 改成condition ,赋值改变了lock的引用 lock = false;// b.notifyAll(); //语句2 lock.notifyAll(); } }}class TestThread extends Thread{ public void run(){ synchronized(TestNotify.lock){ while(TestNotify.lock){// while(TestNotify.lock.getA() == 1){ //改成condition try { TestNotify.lock.wait(); } catch (InterruptedException ex) { Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println(getId()); } }}class A{ int a; public A(int i){ a = i; } public void setA(int i){ a = i; } public int getA() { return a; }}
?