synchronized修饰的方法之间相互调用

时间:2021-05-17 20:19:24

1:synchronized修饰的方法之间相互调用,执行结果为There hello  .。因为两个方法(main,hello)的synchronized形成了互斥锁。  所以当main方法执行完之后,才能执行thread线程中的hello方法。

package test;

import java.util.Random;

/**
* @program: GradleTestUseSubModule
* @author: Yafei Li
* @create: 2018-08-06 10:52
**/
public class Test2 {
public static synchronized void main(String[] args) {
Thread t = new Thread() {
@Override
public void run() {
hello();
}
};
t.start(); try {
Thread.sleep(new Random().nextInt(5000));
} catch (InterruptedException e) { }
System.out.print("There");
} static synchronized void hello() {
try {
Thread.sleep(new Random().nextInt(500));
} catch (InterruptedException e) { }
System.out.print("Hello");
}
}