Java 线程同步 synchronized 和 Lock 锁

线程同步 synchronized 和 Lock 锁

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

  • 处理并发问题,并且某些线程还想修改这个对象,这时候我们就需要线程同步。
  • 相乘同步就是一种等待机制,多个需要同时访问此对象的线程进入对象的等待池形成队列,等待前面线程使用完毕,下一个线程在使用

线程不安全例子

不安全的买票
package com.syn;

/*
    不安全的买票
        线程不安全,有负数
 */
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 void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums<=0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep (100);
        //买票
        System.out.println (Thread.currentThread ().getName ()+"拿到了第 "+ticketNums--+" 张票");
    }
}

在这里插入图片描述

不安全的取钱
package com.syn;

import com.oop.demo05.A;

/*
    不安全的取钱
        两个人取钱,去银行
 */
public class UnsafeBank {
    public static void main (String[] args) {
        //账户
        Account account = new Account (100,"结婚基金");

        Drawing husband = new Drawing (account,50,"husband");
        Drawing wife = new Drawing (account,100,"wife");

        husband.start ();
        wife.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;
        }

        //sleep 可以放大问题的发生性
        try {
            Thread.sleep (1000);
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }

        //卡内余额 = 余额 - 你取出的钱
        account.money = account.money - drawingMoney;
        //你手里的钱
        nowMoney = nowMoney + drawingMoney;

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

在这里插入图片描述

不安全的List
package com.syn;

import java.util.ArrayList;
import java.util.List;

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 (()->{
                list.add (Thread.currentThread ().getName ());
            }).start ();
        }
        Thread.sleep (10);
        System.out.println (list.size ());
    }

}

在这里插入图片描述

队列 和 锁 synchronized

  • 由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题﹐为了保证数据在方法中被访问时的正确性﹐在访问时加入锁机制 synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可﹒存在以下问题:
    • 一个线程持有锁会导致其他所有需要此锁的线程挂起;
    • 在多线程竞争下,加锁﹐释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
    • 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题.
同步方法
  • 由于我们可以通过private关键字来保证数据对象只能被方法访问﹐所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,
  • 它包括两种用法∶synchronized方法synchronized块.
    同步方法:public synchronized void method(int args)
  • synchronized方法控制对“对象”的访问﹐每个对象对应一把锁﹐每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
    缺陷:若将一个大的方法申明为 synchronized 将会影响效率
    synchronized 同步方法,默认锁的是this
package com.syn;

/*
    不安全的买票
        线程不安全,有负数
 */
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 ();
            }
        }
    }

    //synchronized 同步方法,默认锁的是this
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums<=0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep (100);
        //买票
        System.out.println (Thread.currentThread ().getName ()+"拿到了第 "+ticketNums--+" 张票");
    }
}
同步块
synchronized (需要锁的对象){}
  • synchronized (Obj){}
    • Obj可以是任何对象﹐但是推荐使用共享资源作为同步监视器
    • 同步方法中无需指定同步监视器﹐因为同步方法的同步监视器就是this ,就是这个对象本身﹐或者是class
  • 同步监视器的执行过程
    1. 第一个线程访问,锁定同步监视器﹐执行其中代码.
    2. 第二个线程访问﹐发现同步监视器被锁定﹐无法访问.
    3. 第一个线程访问完毕,解锁同步监视器.
    4. 第二个线程访问,发现同步监视器没有锁﹐然后锁定并访问
package com.syn;

import com.oop.demo05.A;

/*
    不安全的取钱
        两个人取钱,去银行
 */
public class UnsafeBank {
    public static void main (String[] args) {
        //账户
        Account account = new Account (1000,"结婚基金");

        Drawing husband = new Drawing (account,50,"husband");
        Drawing wife = new Drawing (account,100,"wife");

        husband.start ();
        wife.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 () {
        //锁 的对象就是变化的量,需要增删改的量
        synchronized (account){
            //判断有没有钱
            if (account.money-drawingMoney<0){
                System.out.println (Thread.currentThread ().getName ()+"钱不够,取不了");
                return;
            }
            //sleep 可以放大问题的发生性
            try {
                Thread.sleep (3000);
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }


            //卡内余额 = 余额 - 你取出的钱
            account.money = account.money - drawingMoney;
            //你手里的钱
            nowMoney = nowMoney + drawingMoney;

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

    }
}

测试JUC安全类型集合

package com.syn;

import java.util.concurrent.CopyOnWriteArrayList;

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

        try {
            Thread.sleep (3*1000);
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }

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

Lock(锁)

  • 从JDK5.0开始,Java提供了更强大的线程同步机制----通过显示定义同步锁对象来实现同步。
  • 同步锁还用Lock对象充当
  • java.util.concurrent.looks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象。
  • ReentrantLock类实现了Lock,他拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可是显示加锁、释放锁

使用方式:

class A{
    private final ReentrantLock lock = new ReentrantLock ();
    public void m(){
        lock.lock ();
        try {
            //保证线程代码安全
        }finally {
            //如果同步代码有异常,要将unlock()写入finally语句块
            lock.unlock ();
        }
    }
}

买票案例

package com.senior;

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main (String[] args) {
        Lock2 lock2 = new Lock2 ();

        new Thread (lock2,"me").start ();
        new Thread (lock2,"you").start ();
        new Thread (lock2,"others").start ();
    }
}
class Lock2 implements Runnable{
    private int ticketNums = 10;

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

    @Override
    public void run () {
        while (true){
            try {
                lock.lock ();//加锁
            if (ticketNums<=0){
                break;
            }else {
                System.out.println (Thread.currentThread ().getName ()+"获得了第 "+ticketNums--+" 票");
            }
            } finally {
                //解锁
                lock.unlock ();
                try {
                    Thread.sleep (10);
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
            }

        }
    }
    
}

synchronized 与 Lock 对比

  • lock是显示锁(手动开启和关闭锁,别忘记关闭锁)synchronized 是隐士锁,出了作用域自动释放
  • Lock 只有代码块锁,synchronized 有代码块锁和方法锁
  • 使用Lock锁,JVM将花费更少的时间调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
  • 优先使用顺序:
    • Lock > 同步代码快(已经进入了方法体,分配了相应资源)> 同步方法(在方法体之外)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只理智汪

你的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值