8锁现象,其实就是关于锁的八个问题,本节我们通过八个问题,逐渐带大家加深对锁的认识,为了方便演示,这里全部用
synchronized演示。
People1 people = new People1();
People1 people2 = new People1();
new Thread(people::eat,"A").start();
TimeUnit.SECONDS.sleep(2);
new Thread(people2::play,"B").start();
new Thread(people2::study,"C").start();public class People1 {
public synchronized void eat() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("synchronized method -> 吃饭");
}
public synchronized void play() {
System.out.println("synchronized method -> 玩耍");
}
public void study() {
System.out.println("synchronized method -> 学习");
}
}synchronized method -> 吃饭
synchronized method -> 玩耍
synchronized method -> 吃饭
synchronized method -> 玩耍
General method -> 学习
synchronized method -> 吃饭
General method -> 学习
synchronized method -> 吃饭
synchronized method -> 玩耍
synchronized method -> 吃饭
总结:synchronized锁的是方法的调用者,这里就是people1,不同的对象对应不同的锁
People2 people = new People2();
People2 people2 = new People2();
new Thread(() -> people.eat(),"A").start();
TimeUnit.SECONDS.sleep(2);
new Thread(() -> people2.play(),"B").start();
new Thread(() -> people2.study(),"C").start();public class People2 {
public static synchronized void eat() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("static synchronized method-> 吃饭");
}
public static synchronized void play() {
System.out.println("static synchronized method-> 玩耍");
}
public synchronized void study() {
System.out.println("synchronized method-> 学习");
}
}static synchronized method-> 吃饭
static synchronized method-> 玩耍
static synchronized method-> 吃饭
static synchronized method-> 玩耍
synchronized method-> 学习
static synchronized method-> 吃饭
synchronized method-> 学习
static synchronized method-> 吃饭
总结:static 修饰的方法属于Class模版,只有一个
相信大家现在应该都明白了吧!
Q.E.D.