多线程(八)synchronized(线程同步)

多个线程操作同一个线程

  • 并发:同一个对象被多个线程同时操作
  • 线程同步:现实生活中,我们会遇到“同一个资源,多个人都想使用”的问题,比如,食堂排队打饭,每个人都想吃饭,最天然的解决班法就是排队,一个个来。
  • 处理多线程问题时, 多个线程访问同一个对象,并且某些线程还想修改这个对象,这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用
  • 由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排他锁,独占资源,其他线程必须等待使用后释放锁即可,存在以下问题
    • 一个线程持有锁会导致其他所有需要此锁的线程挂起;
    • 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
    • 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题。
      三种不安全的案例

/**
 * 不安全的买票
 * 线程不安全
 * @author LCW
 * @since 2020/11/10 19:35
 **/
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"a").start();
        new Thread(buyTicket,"b").start();
        new Thread(buyTicket, "c").start();
    }
}


class BuyTicket implements Runnable{

    //票
    private int ticketNums = 10;

    //外部停止方式
    private boolean flag = true;
    @Override
    public void run() {
        while (flag) {
            buy();
        }
    }

    private void buy() {
        //判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        //模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums-- + "张票");
    }
}

/**
 *
 * 不安全的取钱
 * 两个人去语言行取钱,账户
 * @author LCW
 * @since 2020/11/10 19:41
 **/
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "存款");
        Drawing you = new Drawing(account, 50, "你");
        Drawing girlFriend = new Drawing(account, 100, "女朋友");
        you.start();
        girlFriend.start();

    }

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

    public Account(int money, String name) {
        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() {
        //判断有没有钱
        if (account.money - drawingMoney < 0) {
            System.out.println(Thread.currentThread().getName() + "钱不够了,取不了");
            return;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //卡内余额=余额-你取的钱
        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);
    }
}

/**
 * 不安全的集合
 *
 * @author LCW
 * @since 2020/11/10 20:05
 **/
public class UnsafeList {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();

        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {//两条线程可能同时添加到同个位置
                list.add(Thread.currentThread().getName());
            }).start();
        }
        Thread.sleep(4000);
        System.err.println(list.size());

    }
}

同步方法

  • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包含两种用法:synchronized方法synchronized块
  • 同步方法:public synchronized void method(int args){}
  • synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会堵塞,方法一旦执行,就独占线程,直到该方法返回才释放锁,后面被堵塞的线程才能获得这个锁,继续执行
    • 缺陷:若将一个大的方法申明为synchronized将会影响i效率

同步块

  • 同步块:synchronized(obj){}
  • obj称之为同步监视器
    • obj可以是任何对象,但是推荐使用共享资源作为同步监视器
    • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
  • 同步监视器的执行过程
    • 第一个线程访问,锁定同步监视器,执行其中代码。
    • 第二个线程访问,发现同步监视器被锁定,无法访问。
    • 第一个线程访问完毕,解锁同步监视器。
    • 第二个线程访问,发现同步监视器没有锁,然后锁定并访问

/**
 * 不安全的集合
 *
 * @author LCW
 * @since 2020/11/10 20:05
 **/
public class UnsafeList {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();

        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {//两条线程可能同时添加到同个位置
                synchronized (list) {
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        Thread.sleep(2000);


        System.err.println(list.size());

    }
}

Synchronized和Lock的区别

  • synchronized是Java的关键字,lock是一个类
  • synchronized无法判断获取锁的状态,Lock可以判断是否获得到了锁
  • synchronized 会自动释放锁,lock必须手动释放锁,如果不释放锁,死锁
  • .Synchronized线程1(获得锁,堵塞)、线程2(等待,傻傻的等);lock锁就不一定会等待下去;
  • synchronized 可重入锁,不可以中断,非公平;lock,可重入锁,可以判断锁,非公平(可以自己设置)
  • synchronized 适合锁少量的代码同步问题,lock适合锁大量的同步代码!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值