synchronized的一些理解

1. 两个普通的synchronized

package ThreadTest;

import java.util.concurrent.TimeUnit;

public class ThreadTest02 {
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(phone::sendMsg, "A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        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");
    }
}

这段代码的执行顺序是:
线程A获得phone的锁等待4s,同时main等待1s,因为1s小于4s,所以4s过后线程A打印发信息的函数,瞬间释放锁,线程B拿到锁执行call

2. 两个带有static的同步方法

package ThreadTest;

import java.util.concurrent.TimeUnit;

public class ThreadTest02 {
    public static void main(String[] args) {
        Phone phone1 = new Phone();
        Phone phone2 = new Phone();
        new Thread(()->{
            phone1.sendMsg();
        }, "A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            phone2.call();
        }, "B").start();
    }
}

class Phone{
    public static synchronized void sendMsg(){
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Send message!");
    }
    public static synchronized void call(){
        System.out.println("Call");
    }
}

这段代码实例化两个对象,但是因为两个同步方法是static的,所以是类锁,效果和上面那个一样

3.一个普通的synchorized和一个带有static的同步方法

package ThreadTest;

import java.util.concurrent.TimeUnit;

public class ThreadTest02 {
    public static void main(String[] args) {
        Phone phone1 = new Phone();
        Phone phone2 = new Phone();
        new Thread(()->{
            phone1.sendMsg();
        }, "A").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(()->{
            phone2.call();
        }, "B").start();
    }
}

class Phone{
    public static 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");
    }
}

现在把下面的static删掉,call方法会先执行,因为有两个锁,一个是类锁,一个是对象锁,所以互不影响。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值