Java多线程:线程同步

线程同步

多个线程操作同一个资源

并发

并发:同一个对象被多个线程同时操作

线程同步是一种等待机制,选多个需要同时访问的此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一线程再使用

队列和锁

同一进程的多个线程共享同一块存储空间,在带来方便的同时,也存在访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排他锁,独占资源,其他线程必须等待,使用后释放锁。但存在以下问题:

  • 一个线程持有锁会导致其他需要此锁的线程挂起
  • 在多线程竞争下,加锁、释放锁会导致比较多的上下文切换和调度延时,引起性能问题
  • 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题

线程不安全

线程的内存互不影响,是从同一个地方copy的

不安全的抢票

会发生抢到同一张票,抢到负数张票的问题

//不安全的买票
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 ticketNum = 10;
    boolean flag = true;


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

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

不安全的取钱

//两个人去银行取钱,一个账户
public class UnSafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "A");

        Drawing me = new Drawing(account, 20, 0, "我");
        Drawing me2 = new Drawing(account, 100, 0, "还是我");

        me.start();
        me2.start();
    }
}

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

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//银行:模拟取款
//不设计多线程操作,继承Thread
class Drawing extends Thread{
    Account account;//账户
    int drawingMoney; //取款数量
    int nowMoney; //现金

    public Drawing(Account account, int drawingMoney, int nowMoney, String name){
        super(name);//super()只能写在构造方法的第一行
        this.account = account;
        this.drawingMoney = drawingMoney;
        this.nowMoney = nowMoney;
    }

    //取钱
    @Override
    public void run() {
        //判断余额是否足够
        if (account.money - drawingMoney < 0){
            System.out.println(Thread.currentThread().getName() + ":余额不足");
            return;
        }

        //sleep可以放大问题的放生性
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //更新余额
        account.money = account.money - drawingMoney;
        //现金
        nowMoney = nowMoney + drawingMoney;

        System.out.println(account.name + "的余额为:" + account.money);
        //此处因为继承Thread类,Thread.currentThread().getName() = this.getName()
        System.out.println(this.getName() + "的现金为:" + nowMoney);
    }
}

结果:

A的余额为:-20
A的余额为:-20
我的现金为:20
还是我的现金为:100

不安全的集合

//线程不安全的集合
public class UnSafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 9999; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        //防止部分run方法还没跑完,没来得及添加数据
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

同步方法

synchronized

  • 使用synchronized关键字控制对象的访问,每个对象对应一把锁,每个synchronized方法都必须调用改方法的对象的锁才能执行,否则会阻塞。方法一旦执行,就独占锁,直到该方法返回才释放锁,后续线程才能继续执行。

  • synchronized方法和块

    • 同步方法:同步监视器this
    //同步方法
    public synchronized void method(int args){}
    
    • 同步块:obj称为同步监视器
    synchronized(Obj){}
    
  • 若将大的方法申明为synchronized将会影响效率

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

同步方法

将不安全抢票中的buy()方法申明为synchronized

申明时synchronized默认锁的是this:this是类的实例对象

public synchronized void buy(){
    //判断是否有票
    if (ticketNum <= 0){
        flag = false;
        return;
    }
    System.out.println(Thread.currentThread().getName() + "买了" + ticketNum--);
}

同步块

通过同步块锁上变化的量account

锁的对象该是修改的对象

@Override
public void run() {
    synchronized (account){
        //判断余额是否足够
        if (account.money - drawingMoney < 0){
            System.out.println(Thread.currentThread().getName() + ":余额不足");
            return;
        }

        //sleep可以放大问题的放生性
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //更新余额
        account.money = account.money - drawingMoney;
        //现金
        nowMoney = nowMoney + drawingMoney;

        System.out.println(account.name + "的余额为:" + account.money);
        //此处因为继承Thread类,Thread.currentThread().getName() = this.getName()
        System.out.println(this.getName() + "的现金为:" + nowMoney);
    }
}

JUC安全类型的集合

public class TestJUC {
    public static void main(String[] args) {
        //线程安全的list
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        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());
    }
}

死锁

  • 多个线程各自占有一些共享资源,并互相等待其他线程占有的资源才能运行,在等待中都停止执行的情况
  • 某一个同步块同时拥有两个以上对象的锁时,可能会发生死锁的问题
  • 产生死锁的必要条件:破坏其中一个或多个避免死锁
    1. 互斥条件:一个资源只能被一个进程使用
    2. 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
    3. 不剥夺条件:进程已获得的资源,在未使用完前不能强行剥夺
    4. 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
public class DeadLock {
    public static void main(String[] args) {
        Makeup makeup = new Makeup(0,"0");
        Makeup makeup2 = new Makeup(1, "1");

        makeup.start();
        makeup2.start();
    }
}

//口红
class Lipstick{}

//镜子
class Mirror{}

//化妆
class Makeup extends Thread{

    //需要的资源只有一份,用static保证只有一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;//选择
    String name;//使用者

    Makeup(int choice, String name){
        this.choice = choice;
        this.name = name;
    }

    //化妆
    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //化妆,互相持有对方的锁,需要拿到对方的资源,
    private void makeup() throws InterruptedException {
        if (choice == 0){
            synchronized (lipstick){
                System.out.println(this.name + "获得口红的锁");
                Thread.sleep(1000);
            }
            //一秒后想拿镜子,将锁从锁中拿出,解除死锁
            synchronized (mirror){
                System.out.println(this.name + "获得镜子的锁");
            }
        }else{
            synchronized (mirror){
                System.out.println(this.name + "获得口红的锁");
                Thread.sleep(2000);
            }
            //2秒后拿口红
            synchronized (lipstick){
                System.out.println(this.name + "获得镜子的锁");
            }
        }
    }
}

Lock(锁)

  • JDK5开始,同步锁可以使用Lock对象充当
  • java.util.concurrent.locks.Lock接口控制多个线程对共享资源进行访问。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源前需先获得Lock对象
  • ReentrantLock(可重入锁)类实现了Lock,与synchronized相似
class TestLock2 implements Runnable{
    int ticketNum = 10;

    //定义lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            //先加锁后延时会造成只有一个人拿到票
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            lock.lock();//枷锁,放在try外面防止无锁释放
            //try...finally避免同步代码存在异常
            try {
                if (ticketNum > 0){
                    System.out.println(Thread.currentThread().getName() + "拿到:" + ticketNum--);
                }else{
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}

synchronized与Lock的对比

  • Lock是显示锁,需要手动开启和关闭;synchronized是隐士锁,处理作用域自动释放
  • Lock只有代码块锁,synchronized由代码块锁和方法锁
  • Lock锁花费更少时间调度线程,性能更好,具有更好的扩展性(更多子类)
  • 优先使用顺序:
    • Lock
    • 同步代码块(已进入方法体,分配了相应自由
    • 同步方法(方法体外)
posted @ 2022-04-13 10:12  chachan53  阅读(25)  评论(0编辑  收藏  举报