多线程4:内置锁的重入性

当某个线程请求一个由其它线程持有的锁时,发出请求的线程会进入阻塞状态

由于内置锁是可重入的,因此如果某个线程试图获取一个已经由它自己持有的锁,这个请求可以成功

public final class Child{
	private Object childLock = new Object();
	
	public void doSomething(){
		synchronized(childLock){
			System.out.println("Child do something.");
			this.doSomethingAgain();
		}
	}
	
	public void doSomethingAgain(){
		synchronized(childLock){
			System.out.println("Child do something again.");
		}
	}
	
	public static void main(String[] args){
		Child child = new Child();
		child.doSomething();
	}
}

运行结果:

Child do something.
Child do something again.

 

你可能感兴趣的:(java多线程,内置锁,锁重入)