本篇博客讲述了Java锁和队列的基础知识
Java多线程- 本系列博客为学习Java多线程(狂神说)时所做的笔记
- 本博客内容为线程同步
并发
- 同一个对象被多个线程同时操作
- 处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象。这时候我们就需要线程同步,线程同步其实是一种等待机制,多个需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面的线程使用完毕,下一个线程再使用。
队列和锁
队列和锁的作用:安全性
由于同一进程的多个线程共享同一块存储空间,再带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可,存在以下问题:
三个不安全案例
第一个案例-买票
- 一个线程持有锁会导致其他所有需要此锁的线程挂起。
- 在多线程竞争下,加锁、释放锁会导致比较多的上下文切换 和 调度延时,引起性能问题。
- 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题。
//线程不安全 public class UnsafeBuyTicket { public static void main(String[] args) { BuyTickets station = new BuyTickets(); new Thread(station,"苦逼的我").start(); new Thread(station,"牛逼的你们").start(); new Thread(station,"可恶的黄牛").start(); } } class BuyTickets implements Runnable{ private int ticketNums = 10; private boolean flag = true; @Override public void run() { // 买票 while (flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } public void buy() throws InterruptedException { //判断是否有票 if(ticketNums<=0){ flag = false; return; } //模拟演示,放大问题的发生性 Thread.sleep(1000); //买票 System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--); } }
绝了,我不但要和牛逼的你们抢同一张票,还要和黄牛党抢,黄牛党还TM能拿到第-1张票,后台很硬啊。
很显然,这个线程时不安全的,我们需要一些方式和机制来保证线程的安全。
第二个案例-取钱
//两个人去银行取钱 public class UnsafeBank { public static void main(String[] args) { Account account = new Account(100,"结婚基金"); Drawing you = new Drawing(account,50,"你"); Drawing grilFriend = new Drawing(account,100,"女朋友"); grilFriend.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(){ 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); } }
以上是一个所谓的不安全的银行,两个线程同时操作一个账户
第三个案例-列表
public class UnsafeList { public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<>(); //这里在循环的时候,两个线程同时操作了同一个地址,其中的某一个就被覆盖掉了,就无了 for (int i = 0; i < 10000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } Thread.sleep(3000); System.out.println(list.size()); } } /* //测试JUC安全类型的集合 //这里是一个安全的集合 public class TestJUC { public static void main(String[] args) throws InterruptedException { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); for (int i = 0; i < 10000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } Thread.sleep(3000); System.out.println(list.size()); } } */
以上是一个多线程操作列表的情况,容易出现两个或多个线程同时操作同一块内存地址,导致部分内容被覆盖。
同步方法
- 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两者用法,synchronized方法和synchronized块(将一个方法中需要锁的代码块锁住,来提高一部分效率)。
- 同步方法:public synchronized void method(int args){}
- synchronized方法控制对"对象"的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
- 缺陷:若将一个大的方法申明为synchronized将会影响效率
同步块
- 同步块:synchronized(Obj){}
- Obj称之为同步监视器
- Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class->反射
- 同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码
- 第二个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
取钱案例的修改
public class UnsafeBank { public static void main(String[] args) { Account account = new Account(100,"结婚基金"); Drawing you = new Drawing(account,50,"你"); Drawing grilFriend = new Drawing(account,100,"女朋友"); grilFriend.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); System.out.println(this.getName()+"手里的钱:"+nowMoney); } } }
这里我们将synchronized(account){......}加在run方法里,需要注意的是,synchronized锁的是对象,是当前所在方法的this对象,除非使用同步块并且指定锁的对象。
后面的案例有个小问题:
public class UnsafeBuyTicket { public static void main(String[] args) { BuyTickets station = new BuyTickets(); new Thread(station,"苦逼的我").start(); new Thread(station,"牛逼的你们").start(); new Thread(station,"可恶的黄牛").start(); } } class BuyTickets implements Runnable{ private int ticketNums = 1000; private boolean flag = true; @Override public void run() { // 买票 while (flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void buy() throws InterruptedException { //判断是否有票 if(ticketNums<=0){ flag = false; return; } //买票 //模拟演示,放大问题的发生性 Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--); } }
这里我们在buy方法上加了锁,它锁住的是BuyTickets station这个对象,在运行过程中加入了Thread.sleep(100);也没有什么问题被放大,出现了第一个线程取完了所有票的情况。
当我把票数增加到1000时,开始出现第二个线程和第三个线程,因此,这里应该是没有问题的,只是第一个线程确实在CPU的调度下,比较先的开始抢票。