情况5---两个静态同步方法 ,一部手机
package com.nanjing.juc;
import java.util.concurrent.TimeUnit;
class Phone14 {
// static 静态方法
// 类一加载就有了!锁的是Class
public static synchronized void sendSMS() throws Exception {
TimeUnit.SECONDS.sleep(4);//或者Thread.sleep(4000);
System.out.println(Thread.currentThread().getName()+"---发短信---sendSMS");
}
public static synchronized void sendEmail() throws Exception {
System.out.println(Thread.currentThread().getName()+"---发邮件---sendEmail");
}
}
public class ThreadDemo_14 {
public static void main(String[] args) throws Exception {
Phone14 phone = new Phone14();
new Thread(() -> {
try {
phone.sendSMS();
} catch (Exception e) {
e.printStackTrace();
}
}, "AA").start();
Thread.sleep(100);
new Thread(() -> {
try {
phone.sendEmail();
} catch (Exception e) {
e.printStackTrace();
}
}, "BB").start();
}
}
情况6---两个静态同步方法 ,两部手机
package com.nanjing.juc;
import java.util.concurrent.TimeUnit;
class Phone15 {
// static 静态方法
// 类一加载就有了!锁的是Class
public static synchronized void sendSMS() throws Exception {
TimeUnit.SECONDS.sleep(4);//或者Thread.sleep(4000);
System.out.println(Thread.currentThread().getName()+"---发短信---sendSMS");
}
public static synchronized void sendEmail() throws Exception {
System.out.println(Thread.currentThread().getName()+"---发邮件---sendEmail");
}
}
public class ThreadDemo_15 {
public static void main(String[] args) throws Exception {
Phone15 phone = new Phone15();
Phone15 phone2 = new Phone15();
new Thread(() -> {
try {
phone.sendSMS();
} catch (Exception e) {
e.printStackTrace();
}
}, "AA").start();
Thread.sleep(100);
new Thread(() -> {
try {
phone2.sendEmail();
} catch (Exception e) {
e.printStackTrace();
}
}, "BB").start();
}
}
结果还是一样的,为什么呢?
原因是:对于static静态方法来说,对于整个类Class来说只有一份,
对于不同的对象使用的是同一份方法,相当于这个方法是属于这个类的,
如果静态static方法使用synchronized锁定,那么这个synchronized锁会锁住整个对象!
不管多少个对象,对于静态的锁都只有一把锁,
谁先拿到这个锁就先执行,其他的进程都需要等待!
原文链接:https://blog.csdn.net/ZHOU_VIP/article/details/117232276