Java多线程——同步方法及同步块

· 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块。

  同步方法:public  synchronized  void  method(int  args){}

· synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞。方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。

  缺陷:若将一个大的方法申明为synchronized将会影响效率


同步块

· 同步块:synchronized(obj){}

· obj称之为同步监视器

——obj可以是任何对象,但是推荐使用共享资源作为同步监视器

——同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者时class[反射中讲解]

· 同步监视器的执行过程

  1. 第一个线程访问,锁定同步监视器,执行其中代码;

  2. 第二个线程访问,发现同步监视器被锁定,无法访问;

  3. 第一个线程访问完毕,解锁同步监视器;

  4. 第二个线程访问,发现同步监视器没有锁,然后锁定并进行访问。


代码演示:针对之前不安全案例的改进

一.不安全买票改进

public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"1").start();
        new Thread(station,"2").start();
        new Thread(station,"3").start();

    }
}

class BuyTicket implements Runnable{

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

    @Override
    public void run() {
        //买票
        while (flag){
            try {
                Thread.sleep(1000);
                buy();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    //synchronized同步方法,锁的是this
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums<=0){
            flag = false;
            return;
        }


        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);

    }
}

二.不安全取钱改进

public class UnSafeBank {

    public static void main(String[] args) {
        //账户
        Account account = new Account(1000,"结婚基金");

        Drawing you = new Drawing(account,50,"你");
        Drawing girlFriend = new Drawing(account,100,"girlFriend");

        you.start();
        girlFriend.start();
    }
}


//账户
class Account {
    int money;  //余额
    String name;  //卡名

    public Account(int money, String name) {  //alt + ins  constructor
        this.money = money;
        this.name = name;
    }
}

//银行:模拟取款
class Drawing extends Thread{
    Account account;  //账户
    //取了多少钱
    int drawingMoney;
    //现在手里有多少钱
    int nowMoney;

    public Drawing(Account account,int drawingMoney,String name){
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    //取钱
    @Override
    public void run() {
        
        //锁的对象是变化的量,需要增删改的对象
        synchronized (account){
            //判断有没有钱
            if (account.money - drawingMoney < 0){
                System.out.println(Thread.currentThread().getName()+"余额不足");
                return;
            }

            //sleep放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            account.money = account.money - drawingMoney;
            nowMoney = nowMoney + drawingMoney;

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

三.不安全线程的集合的改进

public class UnSafeList {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        Thread.sleep(3000);
        System.out.println(list.size());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值