synchrnized是可以重入的,但是只允许已经拥有锁的线程重新获得锁,以下写了一个测试代码证实了一件事那就是
一道常用的面试题:
当一个线程进入了一个对象的synchronized修饰的方法A,那么另外一个线程不能进入这个对象的synchronized修饰的方法B
因为synchronized是锁对象的.
public class learnSynchronized {
public synchronized void method1() throws Exception{
System.out.println("method1");
method2();
}
public synchronized void method2() throws Exception{
System.out.println("method2");
Thread.sleep(5000);
}
public synchronized void method3(){
System.out.println("method3");
}
public static void main(String[] args) throws Exception{
final learnSynchronized learnsynchr=new learnSynchronized();
Thread thread1=new Thread(new Runnable() {
@Override
public void run() {
try {
learnsynchr.method1();
}
catch (Exception e){
System.out.println(e.toString());
}
}
});
Thread thread2=new Thread(new Runnable() {
@Override
public void run() {
learnsynchr.method3();
}
});
thread1.start();
thread2.start();
}
}