Java多线程(六):线程同步

线程同步

学习视频:【狂神说Java】多线程详解
up主:遇见狂神说


并发

同一个对象被多个线程同时操控

线程同步

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

锁机制 synchronized
synchronized默认锁的是this

线程同步


同步

同步方法弊端

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


同步块

同步块

示例:

package com.thread;

public class TestSymchronized {
    public static void main(String[] args) {
        Account account = new Account(1000,"结婚基金");

        Drawing you = new Drawing(account,50,"you");
        Drawing she = new Drawing(account,100,"she");

        you.start();
        she.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(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            account.money =account.money-drawingMoney;
            nowMoney = nowMoney+drawingMoney;

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

        }
    }

}

死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。
某一个同步块同时拥有“两个以上的对象的锁”时,就可能发生死锁问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值