Java同步方法及代码块

本文详细介绍了Java中的synchronized关键字,包括同步方法和同步块的使用。同步方法通过对象锁控制对方法的访问,确保同一时间只有一个线程执行。同步块则允许更细粒度的锁控制,可以指定任意对象作为同步监视器。文中还列举了不安全的买票、银行取钱和List集合等例子,说明了同步机制的重要性,并提供了相应的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

同步方法及代码块:synchronized

同步方法
  • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和sychronized块
同步方法:public synchronized void method(int args){}
  • synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个打的方法申明为 synchronized 将会影响效率
同步块
  • 同步块:synchronized(Obj){}
  • Obj:称之为同步监视器
    • Obj可以是任何对象,但是推荐使用共享资源作为同步监视器;
    • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者class。
  • 同步监视器的执行过程
    • 第一个线程访问,锁定同步监视器,执行其中代码;
    • 第二个线程访问,发现同步监视器被锁定,无法访问;
    • 第一个线程访问完毕,解锁同步监视器;
    • 第二个线程访问,发现同步监视器没有锁,然后锁定并访问。
不安全的买票
// 不安全的买票
// 线程不安全
public class Ticked {

    public static void main(String[] args) {
        Buy buy = new Buy();

        new Thread(buy,"云疏").start();
        new Thread(buy,"若瑄").start();
        new Thread(buy,"淼淼").start();
    }
}
public class Buy implements Runnable{

    private int ticketNums = 10;// 票数
    boolean flag = true;// 外部停止方法

    @Override
    public void run() { // 买票

        while (flag){
            //  模拟延时,放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            buyTicket();
        }

    }
    
     public void buyTicket(){ 
        //  判断是否有票
        if(ticketNums <= 0){
            flag = false;
            return;
        }        
        System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNums-- +"票");
    }
}

在这里插入图片描述

  • 解决方案
 public synchronized void buyTicket(){ // 解决方案:在方法中用synchronized修饰方法,给方法+锁
        //  判断是否有票
        if(ticketNums <= 0){
            flag = false;
            return;
        }     
        System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNums-- +"票");
    }
}

在这里插入图片描述

不安全的银行取钱
// 取钱,不安全线程
public class Money {
    public static void main(String[] args) {

        Account account = new Account(100,"结婚基金");
        Bank you = new Bank(account,50,"你");
        Bank girlFriend = new Bank(account,100,"女朋友");

        new Thread(you,"你").start();
        new Thread(girlFriend,"女朋友").start();
    }
}
// 账户
public class Account{
     int money; // 余额
     String name; // 卡名

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}
// 银行 bank
public class Bank implements Runnable{

    Account account;
    int getMoney; // 取了多少钱
    int nowMoney;// 现在手里有多少钱
    String name;
    public Bank(Account account, int getMoney, String name) {
        this.account = account;
        this.getMoney = getMoney;
        this.name = name;
    }

    @Override
    public void run() {
            //        判断有没有钱
            if (account.money - getMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "取不了,钱不够");
                return;
            }

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//        卡内余额
            account.money = account.money- getMoney;
//        你手里的钱
            nowMoney = nowMoney + getMoney;

            System.out.println(account.name+"余额为:"+account.money);
            System.out.println(Thread.currentThread().getName()+"手里的钱为:"+nowMoney);
    }
}

在这里插入图片描述

  • 解决方案
// 银行 bank
public class Bank implements Runnable{

    Account account;
    int getMoney;
    int nowMoney;
    String name;
    public Bank(Account account, int getMoney, String name) {
        this.account = account;
        this.getMoney = getMoney;
        this.name = name;
    }

    @Override
    public void run() {
        synchronized (account){ // 用同步代码块来加锁
            
            if (account.money - getMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "取不了,钱不够");
                return;
            }

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money = account.money- getMoney;
            nowMoney = nowMoney + getMoney;

            System.out.println(account.name+"余额为:"+account.money);
            System.out.println(Thread.currentThread().getName()+"手里的钱为:"+nowMoney);
        }
    }
}

在这里插入图片描述

不安全的List集合
public class ListDemo {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {                
               list.add(Thread.currentThread().getName());              
            }).start();
        }
        
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println(list.size()); // 输出集合总长度
    }
}

在这里插入图片描述

  • 解决方案
public class ListDemo {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();

        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {   
            	synchronized(list){  // 用同步代码块加锁
            		 list.add(Thread.currentThread().getName());         
            	}
                   
            }).start();
        }
        
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println(list.size()); // 输出集合总长度
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魏小祖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值