线程的同步

线程同步

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

同步方法:

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

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

是在方法面前添加synchronized关键字的方法
语法: synchronized void f(){}

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 synchronized void   buy() throws InterruptedException {
        if (ticketNums<=0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(1000);
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }

同步块:synchronized(Obj){}

  Obj称之为同步监视器
  		Obj可以是任何对象,但是推荐使用共享资源作为同步监视器;
  		同步方法中无需指定同步监视器,因为同步方法的同步监视器对象就是对象本身,或者是class;
  	同步监视器的执行过程
  		1、第一个线程访问,锁定同步监视器,执行其中的代码
  		2、第二个线程访问,发现同步监视器被锁定,无法访问;
  		3、第一个线程访问完毕,解锁同步监视器;
  		4、第二个线程访问,发现同步监视器没有锁,然后锁定并访问
public class UnsafeBank {
    public static void main(String[] args) {


        //账户
        Account account = new Account(100, "结婚基金");

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

        girlFriend.start();
        you.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);
                //Thread.currentThread().getName() = this.getName();
                System.out.println(this.getName() + "手里的钱:" + nowMoney);
            }
        }

    }

线程的同步

public class UnsafeList {
    public static void main(String[] args) {
        List<String> list  = new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
               
               //对list集合进行监视
               synchronized (list) {
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值