我想证明下,一个线程锁住一个对象后,与此同时别的线程还可以执行另外的方法。
public class TestTT implements Runnable
{
int i=100;
public synchronized void m1() throws Exception
{
i=1000;
Thread.sleep(10000);
System.out.println("b= "+i);
}
public void m2()
{
System.out.println(i);
}
public void run()
{
try{
m1();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
TestTT tt=new TestTT();
Thread t=new Thread(tt);
t.start();
try{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
tt.m2();//为什么会输出1000?m1上锁之后主线程不是看不到m1里面的内容吗?
}
}
public class TestTT implements Runnable
{
int i=100;
public synchronized void m1() throws Exception
{
i=1000;
Thread.sleep(10000);
System.out.println("b= "+i);
}
public void m2()
{
System.out.println(i);
}
public void run()
{
try{
m1();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
TestTT tt=new TestTT();
Thread t=new Thread(tt);
t.start();
try{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
tt.m2();//为什么会输出1000?m1上锁之后主线程不是看不到m1里面的内容吗?
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货