线程同步机制

线程同步:
由于同一进程的多个线程共享同一块储存空间,在带来方便的同时,也带来了访问
冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,
当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。
存在一下问题:
    1、一个线程持有锁会导致其他所有需要此锁的线程挂起;
    2、在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
    3、如果一个优先级高的线程等待一个优先级低的线程释放锁 会导致优先级倒置,引起性能问题。

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

测试代码1:

//不安全买票
//线程不安全
public class UnsafeBuyTicket
{
    public static void main(String[] args)
    {
        BuyTicket station = new BuyTicket();

        new Thread(station,"苦逼的我").start();
        new Thread(station,"厉害的你们").start();
        new Thread(station,"可恶的黄牛党").start();
    }
}

class BuyTicket implements Runnable{

    //票
    private int ticketNums = 10;
    //外部停止标志
    boolean flag = true;

    @Override
    public void run()
    {
        while (flag){
            try
            {
                buy();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

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

测试代码2:

//不安全的取钱
//两人去银行取钱
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,"女朋友");

        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;
    }

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

            //模拟延时,放大问题
            try
            {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

            //System.out.println(account.name+"余额为:"+account.money);

            account.money = account.money - drawingMoney;

            nowMoney = nowMoney + drawingMoney;

            System.out.println(this.getName()+"取款"+drawingMoney);
            System.out.println(account.name+"余额为:"+account.money);
            System.out.println(this.getName()+"手里的钱为:"+nowMoney);
        }
    }
}

测试代码3:

//线程不安全的集合
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(3000);
        System.out.println(list.size());
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值