public class TT implements Runnable
{
int b = 100;
public synchronized void m1() throws Exception
{
b = 1000;
Thread.sleep( 5000 );
System.out.println( "b = " + b );
}
public void m2()
{
System.out.println( b ) ;
}
public void run()
{
try { m1(); }
catch( Exception e ) {}
}
public static void main(String[] args) throws Exception
{
TT tt = new TT();
Thread t = new Thread( tt ) ;
t.start();
Thread.sleep( 1000 );
tt.m2();
}
} 这程序的运行结果为 1000;
b = 1000 为什么?在mian方法运行tt.m2();时m1();给锁住了,不对吗? 那怎么会访问到m1()里的b值呢?
如果去掉Thread.sleep( 1000 ); 那运行结果为 100
b = 1000
{
int b = 100;
public synchronized void m1() throws Exception
{
b = 1000;
Thread.sleep( 5000 );
System.out.println( "b = " + b );
}
public void m2()
{
System.out.println( b ) ;
}
public void run()
{
try { m1(); }
catch( Exception e ) {}
}
public static void main(String[] args) throws Exception
{
TT tt = new TT();
Thread t = new Thread( tt ) ;
t.start();
Thread.sleep( 1000 );
tt.m2();
}
} 这程序的运行结果为 1000;
b = 1000 为什么?在mian方法运行tt.m2();时m1();给锁住了,不对吗? 那怎么会访问到m1()里的b值呢?
如果去掉Thread.sleep( 1000 ); 那运行结果为 100
b = 1000
{
TT tt = new TT();
Thread t = new Thread( tt ) ;
//启动一个线程,
t.start();
//到此,此时上面的那个线程可以执行了b = 1000; ,并且开始sleep,休眠5秒,
Thread.sleep( 1000 );
//而主线程1秒后执行tt.m2()方法,当然打的是1000了
tt.m2(); } 也就是说你启动的那个线程和主线程是并行运行的,
所以没有去掉Thread.sleep( 1000 )的时候是打印的1000
而不去掉Thread.sleep( 1000 ),B来不及等到赋新值,线程就已经运行到了.
{
int b = 100;
public synchronized void m1() throws Exception
{
//b = 1000; 就是这个原因,把b的赋值放在sleep之后就清楚了
Thread.sleep( 5000 );
b = 1000;
System.out.println( "b = " + b );
}
public void m2()
{
System.out.println( b ) ;
}
public void run()
{
try{
m1();
} catch( Exception e ) {
}
}
public static void main(String[] args) throws Exception
{
Test1 tt = new Test1();
Thread t = new Thread( tt ) ;
t.start();
Thread.sleep( 1000 );
tt.m2();
}
}
锁住一个方法,并不是这个方法就是一个事务,而是不能在未解锁的情况下再次访问这个方法而已
m1()锁住了是没错,但是仅仅是其他线程不能访问m1而已,这和m1中对其他的变量操作没有关系