同步方法及同步块

HeJin大约 4 分钟Java多线程详解

由于我们可以通过 private关键字来保证数据对象只能被方法访问。所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字。它包括两种用法:synchronized方法synchronized块

同步方法

同步方法: public synchronized void method(int args){}

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

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

方法里面需要修改的内容才需要锁,锁得太多,浪费资源。

同步块

同步块:synchronized(obj){}

obj称之为同步监视器

  • obj可以是任何对象,但是推荐使用共享资源作为同步监视器
  • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class[反射中讲解]。

同步监视器的执行过程

  1. 第一个线程访问,锁定同步监视器,执行其中代码。
  2. 第二个线程访问,发现同步监视器被锁定,无法访问。
  3. 第一个线程访问完毕,解锁同步监视器。
  4. 第二个线程访问,发现同步监视器没有锁,然后锁定并访问。

安全的买票

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();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * synchronized 同步方法。锁得是this
     */
    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if (ticketNums <= 0){
            flag = false;
            return;
        }
        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
    }
}
苦逼的我拿到了第10张票
可恶的黄牛党拿到了第9张票
牛逼的你们拿到了第8张票
苦逼的我拿到了第7张票
可恶的黄牛党拿到了第6张票
牛逼的你们拿到了第5张票
苦逼的我拿到了第4张票
可恶的黄牛党拿到了第3张票
牛逼的你们拿到了第2张票
苦逼的我拿到了第1张票

Process finished with exit code 0

安全的取钱

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,"girlFriend");

        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() {
        // 锁得对象是变化的量:需要增删改
        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 = account.money - drawingMoney;
            // 手里的钱
            nowMoney = nowMoney + drawingMoney;

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

结果1:

结婚基金余额为:950
你手里的钱:50
结婚基金余额为:850
girlFriend手里的钱:100

Process finished with exit code 0

结果2:

结婚基金余额为:900
girlFriend手里的钱:100
结婚基金余额为:850
你手里的钱:50

Process finished with exit code 0

安全的集合

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(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}
10000

Process finished with exit code 0

当去掉延时的时候,发现打印的小于10000。这是因为打印语句是由主线程执行的,主线程虽然执行完了(电脑性能太好),但是往集合中添加元素的线程还没有执行完。这样打印结果就小于10000了。但是此时还是线程安全。