一个关于使用String做锁的问题(PS:不要使用string做锁)

来源:互联网 发布:彭雪茹 知乎 编辑:程序博客网 时间:2024/05/19 05:31
今天写一段程序,里面有一个锁的嵌套,在里面,我wait释放了一个锁,另一个锁并没有释放,但是在运行的时候,没有释放的锁竟然能够获得。
package Thread.test;/** * @author Administrator */public class NotifyTestString {public static class Thread1 implements Runnable {public String lock;public String lockAfter;public Thread1(String lock, String lockAfter) {this.lock = lock;this.lockAfter = lockAfter;}public void run() {synchronized (lock) {synchronized (lockAfter) {while (true) {lockAfter.notify();System.out.println(" lockAfter notified! ");try {System.out.println("try to wait!");lock.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("the end of  synchronized code locked by lockAfter!");}}}}}public static void main(String[] args) throws InterruptedException {String lockAfter = "";String lock = "";Thread1 t1 = new Thread1(lock, lockAfter);new Thread(t1).start();Thread.currentThread().sleep(100);synchronized (lockAfter) {System.out.println("gain the lock");}}}

这段代码会打印出gain the lock,这就奇怪了,我释放的是lock锁,并没有释放lockAfter锁啊,为什么主线程还能获得lockAfter锁呢?

难道wait把两个锁全部释放了?这不可能啊!jdk中明明写的非常清楚

Note that the <tt>wait</tt> method, as it places the current thread 
     * into the wait set for this object, unlocks only this object; any 
     * other objects on which the current thread may be synchronized remain 
     * locked while the thread waits.


瞅了一下,晕,最初级的一个错误,自己的两个String是同一个对象,因为如果是直接将字符串赋给一个String变量的话,jvm会首先在字符串池中看看有没有,没有的话,就创建一个字符串,放进字符串池中,然后返回引用,如果有的话,就返回池中的这个,我这样声明的两个字符串其实是一个,就是说,两次获得的锁其实是一个,这就是为什么锁获得到的原因,

0 0
原创粉丝点击