[求助]关于多线程的运行结果, 请教大牛们
飞火流云 2010-02-24 04:56:38 源码如下:
public class TestThread implements Runnable{
int b =100 ;
public synchronized void m1() throws InterruptedException{
b=1000;
Thread.sleep(5000);
System.out.println("m1(): b="+b);
}
public synchronized void m2() throws InterruptedException{
Thread.sleep(2500);
System.out.println("-------------");
b=2000;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
m1();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
TestThread tr = new TestThread();
Thread tt = new Thread(tr);
tt.start();
tr.m2();
System.out.println("主线程 : b="+tr.b);
// Thread.sleep(1000);
// System.out.println("主线程 : b="+tr.b);
Thread.sleep(10000);
System.out.println("最后结果 : b="+tr.b);
}
}
运行结果:
-------------
主线程 : b=1000
m1(): b=1000
最后结果 : b=1000
这里不明白的是, synchronized的作用不是不同线程只能在同一个对象上加一把锁么?既然一个对象只能有一把锁的话, 那用两个synchronized方法同步访问还是有问题,还不如直接把对象给锁住呢。。。