日期:2014-05-20  浏览次数:20633 次

想测试下synchronized关键字,有点不明白
package Test;

public class TestThreadSync implements Runnable{

public TestThreadSync(){

}
Sync sync = new Sync();

@Override
public void run() {
synchronized (sync){
sync.function();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public static void main(String args[]){
Thread t1 = new Thread(new TestThreadSync());
Thread t2 = new Thread(new TestThreadSync());
t1.start();
t2.start();
}

}

class Sync{

public Sync(){

}

public void function(){
System.out.println(Thread.currentThread().getName()+"正在运行。。。");
}


}
我的想法是t1,t2启动,打印“Thread-0正在运行。。。”5秒钟后再打印“Thread-1在运行。。。”为什么他们同时打印出来呢  synchronized不是把对象锁定了吗5秒后才释放的?请各位指点下
------解决方案--------------------
代码改一下:
	public static void main(String args[])
{
TestThreadSync tts= new TestThreadSync();//只创建一个TestThreadSync对象,
Thread t1 = new Thread(tts);             //里面的sync是一个。才能起到同步的作用。
Thread t2 = new Thread(tts);
t1.start();
t2.start();
}