概念:当一个线程得到一个对象锁后,再次请求此对象锁可以重新得到该对象锁。
1、实现类:
package cn.brian.reentry;
/**
* @package : cn.brian.reentry
* @author : juque
* @date : 2018-08-27 15:44:37
* @description : 锁的重入。synchronized锁的是对象,在执行到sayHello2时,线程又重新获取了新的锁,所以没有产生死锁。而因为锁的是对象,所以一直到线程9执行完,线程10才开始执行
*
*/
public class MyRunnable implements Runnable {
/*
* (non-Javadoc)
*
* @Title: run
*
* @Description: TODO
*
* @see java.lang.Runnable#run()
*/
public void run() {
synchronized (this) {
sayHello1();
sayHello2();
}
}
public void sayHello1() {
System.out.println(Thread.currentThread().getName() + ";-->say hello one!");
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized public void sayHello2() {
System.out.println(Thread.currentThread().getName() + ";-->say hello two!");
try {
Thread.currentThread().sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2、main方法:
package cn.brian.reentry;
/**
* @package : cn.brian.reentry
* @author : juque
* @date : 2018-08-27 15:51:04
* @description : TODO
*
*/
public class Test {
/**
* @Title : main
* @Description : mian方法
* @param args
* @return: void
* @author : juque
* @date : 2018-08-27 15:51:04
*/
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
Thread thread1 = new Thread(myRunnable);
thread1.start();
}
}
3、运行结果:
Thread-9;-->say hello one!
Thread-9;-->say hello two!
Thread-10;-->say hello one!
Thread-10;-->say hello two!
结论:在执行到sayHello2时,线程9又重新获取了新的锁,所以没有产生死锁。而因为是对象锁,所以一直到线程9执行完,线程 10才开始执行run模块代码