情况7---一个静态同步方法、一个普通同步方法、一个对象调用
package com.nanjing.juc;
import java.util.concurrent.TimeUnit;
class Phone16 {
// static 静态方法
// 类一加载就有了!锁的是Class
public static synchronized void sendSMS() throws Exception {
TimeUnit.SECONDS.sleep(4);//或者Thread.sleep(4000);
System.out.println(Thread.currentThread().getName()+"---发短信---sendSMS");
}
public synchronized void sendEmail() throws Exception {
System.out.println(Thread.currentThread().getName()+"---发邮件---sendEmail");
}
}
public class ThreadDemo_16 {
public static void main(String[] args) throws Exception {
Phone16 phone = new Phone16();
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();
}
}
总结:
因为一个锁的是Class类的模板,一个锁的是对象的调用者。所以不存在等待,直接运行。
所以去掉延时4秒后,还是AA线程先执行
package com.nanjing.juc;
class Phone16 {
// static 静态方法
// 类一加载就有了!锁的是Class
public static synchronized void sendSMS() throws Exception {
//TimeUnit.SECONDS.sleep(4);//或者Thread.sleep(4000);
System.out.println(Thread.currentThread().getName()+"---发短信---sendSMS");
}
public synchronized void sendEmail() throws Exception {
System.out.println(Thread.currentThread().getName()+"---发邮件---sendEmail");
}
}
public class ThreadDemo_16 {
public static void main(String[] args) throws Exception {
Phone16 phone = new Phone16();
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();
}
}