[JavaSE学习之旅]线程同步

线程同步

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

不安全的样例

  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 tickerNum = 10;
    private boolean flag = true;

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

    private void buy() throws InterruptedException {
        //判断是否有票
        if(tickerNum<=0){
            flag = false;
            return;
        }

        //模拟延时
        Thread.sleep(100);

        System.out.println(Thread.currentThread().getName()+"拿到"+tickerNum--);
    }
}

结果:

在这里插入图片描述

  1. 不安全的取钱
//不安全的取钱
//两个人去银行取钱,账户
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,"girlFriend");

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

//账户
class Account{
    //余额
    int money;

    //卡号
    String name;

    public Account(String name) {
        this.name = 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 -= drawingMoney;

        nowMoney += drawingMoney;

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

结果:

在这里插入图片描述

  1. 线程不安全的集合
import java.util.ArrayList;
import java.util.List;

//线程不安全的集合
public class UnsafeList {
    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(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

结果:

在这里插入图片描述

同步方法

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

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

  • 方法里需要修改的内容才需要锁,锁的东西太多,浪费资源

  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 tickerNum = 10;
    private boolean flag = true;

    @Override
    public void run() {
        while(flag){
            try {
                buy();
                //模拟延时
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

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



        System.out.println(Thread.currentThread().getName()+"拿到"+tickerNum--);
    }
}

结果:

在这里插入图片描述

修改了哪些:buy方法增加了synchronized关键字,sleep放在run方法中

同步块

  • 同步块:synchronized(Obj){}

  • Obj称之为同步监视器

    • Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
    • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是对象本身,或者是class【反射中讲解】
  • 同步监视器的执行过程

    1. 第一个线程访问,锁定同步监视器,执行其中代码
    2. 第二个线程访问,发现同步监视器被锁定,无法访问
    3. 第一个线程访问完毕,解锁同步监视器
    4. 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
  1. 将不安全的取钱修改为安全的取钱
//不安全的取钱
//两个人去银行取钱,账户
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,"girlFriend");

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

//账户
class Account{
    //余额
    int money;

    //卡号
    String name;

    public Account(String name) {
        this.name = 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();
            }
            account.money -= drawingMoney;

            nowMoney += drawingMoney;

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

    }
}

结果:

在这里插入图片描述

解答:为什么锁run方法没用而用同步代码块锁account对象?

因为同步方法默认锁的是this当前对象,这个样例中进入run方法的对象有you和girlFriend两个对象,you进入run方法锁住的是you这个对象,girlFriend进入run方法锁住的是girlFriend对象,并不能保证他们先后访问账户,我们不应该锁银行,应该锁的是账户,要锁的是变化的量

  1. 将线程不安全的集合修改为线程安全的集合
//线程不安全的集合
public class UnsafeList {
   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(10000);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       System.out.println(list.size());
   }
}

结果:

在这里插入图片描述

将变化的量list锁住

CopyOnWriteArrayList

CopyOnWriteArrayList这个类是线程安全的类,可以实现集合自己同步

import java.util.concurrent.CopyOnWriteArrayList;

//测试JUC安全类型的集合
public class TestJUC {
    public static void main(String[] args) throws InterruptedException {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
               list.add(Thread.currentThread().getName());
            }).start();
        }

        Thread.sleep(3000);

        System.out.println(list.size());
    }
}

结果:
在这里插入图片描述

让我们一起变得更强

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值