8锁问题
8锁问题
public class Test1 {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();
new Thread(phone::sendMsg,"A").start();
Thread.sleep(1000);
new Thread(phone::call,"B").start();
}
}
class Phone{
public synchronized void sendMsg() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("send message");
}
public synchronized void call() {
System.out.println("call");
}
}
synchronized锁的是方法的调用者 (phone对象)所以发短信先获取到锁,永远是先打印发短信。
public class Test1 {
public static void main(String[] args) throws InterruptedException {
Phone phone = new Phone();
new Thread(phone::sendMsg,"A").start();
Thread.sleep(1000);
new Thread(phone::call,"B").start();
}
}
class Phone{
public synchronized void sendMsg() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("send message");
}
public void call() {
System.out.println("call");
}
}
如果打电话没加synchronized关键字为普通方法,那么将不受锁的影响 ,即使发短信没有运行完,那么他也可以抢先执行
public class Test1 {
public static void main(String[] args) throws InterruptedException {
Phone phone1 = new Phone();
Phone phone2 = new Phone();
new Thread(phone1::sendMsg,"A").start();
// Thread.sleep(1000);
new Thread(phone2::call,"B").start();
}
}
class Phone{
public synchronized void sendMsg() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("send message");
}
public synchronized void call() {
System.out.println("call");
}
}
设立了两个实例对象phone1,phone2,因为synchronized锁的是方法的调用者 。所以两个对象的锁不受影响,
好比非同步方法。
public class Test1 {
public static void main(String[] args) throws InterruptedException {
Phone phone1 = new Phone();
Phone phone2 = new Phone();
new Thread(() -> {
phone1.sendMsg();
}, "A").start();
new Thread(() -> {
phone2.call();
}, "B").start();
}
}
class Phone {
public static synchronized void sendMsg() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("send message");
}
public static synchronized void call() {
System.out.println("call");
}
}
static 关键字是静态方法,静态方法锁的是class模板,即使有两个对象也会受到锁的控制。
public class Test1 {
public static void main(String[] args) throws InterruptedException {
Phone phone1 = new Phone();
Phone phone2 = new Phone();
new Thread(() -> {
phone1.sendMsg();
}, "A").start();
new Thread(() -> {
phone2.call();
}, "B").start();
}
}
class Phone {
public static synchronized void sendMsg() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("send message");
}
public synchronized void call() {
System.out.println("call");
}
}
两个执行方法一个为静态同步方法,一个为普通同步方法,一个锁的是对象,一个锁的是class ,两个不同锁的互不影响,因为延迟的存在,所以还是先执行call

浙公网安备 33010602011771号