大家看下下面两个同步程序的对比。
程序一: TestB 的对象b加锁。 运行后证明锁有效。输出结果
m_one:2000
m2:2000
m_two:1000
class TestB {
public Integer num;
public TestB(Integer num){
this.num=num;
}
}
public class Tsynchronized2 implements Runnable{
TestB b=new TestB(100);
public void m1(){
System.out.println("m_one:"+b.num);
synchronized(b){
b.num=1000;
System.out.println("m_two:"+b.num);
}
try{
Thread.sleep(1500);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
public void m2() throws Exception{
synchronized(b){
b.num=2000;
Thread.sleep(2000);
}
System.out.println("m2:"+b.num);
}
@Override
public void run() {
// TODO Auto-generated method stub
m1();
}
public static void main(String[] args) throws Exception{
Tsynchronized2 ts=new Tsynchronized2();
Thread t=new Thread(ts);
t.start();
ts.m2();
}
}
把上面的程序小改一下
上面程序的加锁的对象TestB更换成 Integer对象b。其他逻辑是一样的。同样是对b加锁。锁失效了。
我现在是百思不得其姐啊。。。。
下面程序的运行结果是:
m_one=2000
m_two=1000
m2=1000
public class Tsynchronized implements Runnable{
Integer b=new Integer(100);
public void m1(){
System.out.println("m_one:"+b.intValue());
synchronized(b){
b=1000;
System.out.println("m_two:"+b.intValue());
}
try{
Thread.sleep(1500);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
public void m2() throws Exception{
synchronized(b){
b=2000;
Thread.sleep(2000);
}
System.out.println("m2:"+b.intValue());
}
@Override
public void run() {
// TODO Auto-generated method stub
m1();
}
public static void main(String[] args) throws Exception{
Tsynchronized ts=new Tsynchronized();
Thread t=new Thread(ts);
t.start();
ts.m2();
}
}
哪位大神帮忙解释一下啊 。加锁的都是对象,只不过换了个对象的写法。为什么一个锁有效,一个锁无效呢?
------解决方案--------------------
Integer b;
b=1000;
b=2000;
你这样赋值以后,b就不是原来那个对象了,当然锁不住。
而b.num=1000;更改的是b的成员变量num,b还是没有变,所以有效。
------解决方案--------------------
一楼目测正解。。。
膜拜~
------解决方案--------------------
进来 学习一下!!!
------解决方案--------------------
