即在使用synchronized时,当一个线程得到一个对象锁后,再次请求此对象锁时,是可以再次得到该对象的锁的。也就是说在一个synchronized方法或块的内部调用本类的其他synchronized方法或块时,是永远可以得到锁的
class Service{
public synchronized void service1(){
System.out.println("service 1 ");
service2();
}
public synchronized void service2(){
System.out.println("service 2");
service3();
}
public synchronized void service3(){
System.out.println("service 3");
}
}
class MyThread extends Thread{
@Override
public void run() {
Service service = new Service();
service.service1();
}
}
public class Run {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
可重入锁即自己可以再次获取自己的内部锁,反之不可重入锁就造成死锁了
而且在继承环境中子类可以调用父类的同步方法
class Father{
public int i = 10;
public synchronized void operateFather(){
i--;
System.out.println("Father i " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Son extends Father{
public synchronized void operateSon(){
try {
while(true){
i--;
System.out.println("Son i " + i);
Thread.sleep(100);
operateFather();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread extends Thread{
@Override
public void run() {
Son son = new Son();
son.operateSon();
}
}
public class Run {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
结果:
Son i 9
Father i 8
Son i 7
Father i 6
Son i 5
Father i 4
Son i 3
Father i 2
Son i 1
Father i 0
Son i -1
Father i -2
Son i -3
Father i -4
.......
在继承关系中,同步是不可继承的:
class Father{
public int i = 10;
public synchronized void operate(){
i--;
System.out.println("Father i " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Son extends Father{
public void operate(){
try {
while(true){
i--;
System.out.println(Thread.currentThread().getName() + " Son i " + i);
Thread.sleep(100);
operate();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThreadA extends Thread{
private Son son;
public MyThreadA(Son son){
this.son = son;
}
@Override
public void run() {
son.operate();
}
}
class MyThreadB extends Thread{
private Son son;
public MyThreadB(Son son){
this.son = son;
}
@Override
public void run() {
son.operate();
}
}
public class Run {
public static void main(String[] args) {
Son son = new Son();
MyThreadA a = new MyThreadA(son);
MyThreadB b = new MyThreadB(son);
a.setName("A");
b.setName("B");
a.start();
b.start();
}
}
结果:
A Son i 9
B Son i 8
B Son i 7
A Son i 7
A Son i 5
B Son i 5
A Son i 3
B Son i 3
虽然在父类中方法是同步的,但是子类重写之后,方法不同步了,同步没有继承性