同一个类中两个synchronized方法和一个普通方法的调用问题
不同线程分别调用同一个对象的两个不同synchronized方法,先拿到锁先执行
// 手机类
public class LockTest01 {
public static void main(String[] args) throws InterruptedException {
Phone phone=new Phone();
// 打电话
new Thread(()->phone.call()).start();
// 睡眠1s
TimeUnit.MILLISECONDS.sleep(1000L);
// 发短信
new Thread(()->phone.sendMsg()).start();
}
}
// 手机类
class Phone{
// 打电话
public synchronized void call() {
try {
TimeUnit.MILLISECONDS.sleep(3000L);
System.out.println("打电话");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 发短信
public synchronized void sendMsg(){
System.out.println("发短信");
}
// say hello
public void sayHello(){
System.out.println("hello");
}
}
结果
同一个对象中的两个synchronized方法被不同线程调用,先拿到锁的方法一定先执行,因为锁的是同一个对象,一个同步方法拿到锁,另一个同步方法需要等待释放锁
非同步方法不受锁影响
public class LockTest02 {
public static void main(String[] args) throws InterruptedException {
Phone phone=new Phone();
// 打电话
new Thread(()->phone.call()).start();
// 睡眠1s
TimeUnit.MILLISECONDS.sleep(1000L);
// 发短信
new Thread(()->phone.sendMsg()).start();
// say hello
new Thread(()->phone.sayHello()).start();
}
}
// 手机类
class Phone{
// 打电话
public synchronized void call() {
try {
TimeUnit.MILLISECONDS.sleep(4000L);
System.out.println("打电话");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 发短信
public synchronized void sendMsg(){
System.out.println("发短信");
}
// say hello
public void sayHello(){
System.out.println("hello");
}
}
结果
这里hello先执行,对比上一个测试,只是把打电话的同步方法延迟加长到4s,call()的线程先拿到锁,所以打电话比发短信一定先执行,而hello不是同步方法,不受锁的影响是正常执行的。
这里的执行顺序:call()方法先拿到锁,此时main线程继续执行睡眠1s,与此同时call()同步方法进入睡眠4s,main线程睡眠完毕继续往后执行,到sendMsg()同步方法开启线程但是需要等待锁,main线程正常执行sayHello()方法,打印hello,call()方法休眠4s完毕继续执行完成释放锁,打印“打电话”,sendMsg()方法拿到锁开始执行,完成打印“发短信”