• [多线程] | 实例演示三种创建多线程的方式,初识线程同步以及解决线程安全问题(超卖)


     🍳作者:天海奈奈

    💭眼过千遍不如手锤一遍:推荐一款模拟面试,斩获大厂 o f f e r ,程序员的必备刷题平台 − − 牛客网 

    👉🏻点击开始刷题之旅

    目录

    前言

    1 创建多线程的三种方式

    不加线程

    1 继承Thread类来实现多线程

    1 单线程

     2 多线程 

    2 Runnable接口

    3 Callable接口

    4  小结

    2 线程同步

    现实生活中:

    代码中:

    代码实现

    3 synchronized的锁对象

    4 线程安全的产生及解决方式

    实例,杜绝电商秒杀活动中“超卖”现象。


    前言

    读这篇文章前请先了解什么是程序,什么是线程,什么是进程以及并行与并发的概念,这里主要是进行代码的实现去了解具体创建线程的操作,认识线程同步,锁以及如何解决线程安全问题

    1 创建多线程的三种方式

    我们考虑用一个情景来演示,假设我们有三个跑步参赛者,我们记录每秒参赛者跑的距离

    不加线程

    1. public class FirstThread {
    2. public static void main(String[] args) {
    3. //前一行执行下一行才能执行,并不能做到并行执行
    4. System.out.println("参赛者A 10秒跑了 1");
    5. System.out.println("参赛者B 10秒跑了 10");
    6. System.out.println("参赛者C 10秒跑了 100");
    7. }
    8. }

    显而易见,只通过打印时无法实现多线程的与实现每秒进行的。

    1 继承Thread类来实现多线程

    1 单线程

    1. public class FirstThread {
    2. //线程内部类
    3. class Runner extends Thread{
    4. //重写run方法
    5. @Override
    6. public void run() {
    7. //跑步速度 生成一个随机数
    8. Integer speed = new Random().nextInt(10);
    9. //10秒跑了多少
    10. for(int i = 1;i <= 10;i++){
    11. try {
    12. Thread.sleep(1000);//休眠一秒
    13. } catch (InterruptedException e) {
    14. e.printStackTrace();
    15. }
    16. System.out.println("第" + i +"秒" +this.getName() + "跑了:" + i*speed +"米");//this.getName()获取当前线程名
    17. }
    18. }
    19. }
    20. public void start(){
    21. Runner threadA = new Runner();
    22. threadA.setName("参赛者A");
    23. threadA.start();//开始新线程的创建与运行
    24. }
    25. public static void main(String[] args) {
    26. //前一行执行下一行才能执行,并不能做到并行执行
    27. new FirstThread().start();//对类进行实例化并调用里面的start方法
    28. }
    29. }

     

     2 多线程 

    1. public class FirstThread {
    2. //线程内部类
    3. class Runner extends Thread{
    4. //重写run方法
    5. @Override
    6. public void run() {
    7. //跑步速度 生成一个随机数
    8. Integer speed = new Random().nextInt(10);
    9. //10秒跑了多少
    10. for(int i = 1;i <= 10;i++){
    11. try {
    12. Thread.sleep(1000);//休眠一秒
    13. } catch (InterruptedException e) {
    14. e.printStackTrace();
    15. }
    16. System.out.println("第" + i +"秒" +this.getName() + "跑了:" + i*speed +"米");//this.getName()获取当前线程名
    17. }
    18. }
    19. }
    20. public void start(){
    21. Runner threadA = new Runner();
    22. threadA.setName("参赛者A");
    23. Runner threadB = new Runner();
    24. threadB.setName("参赛者B");
    25. Runner threadC = new Runner();
    26. threadC.setName("参赛者C");
    27. threadA.start();//开始新线程的创建与运行
    28. threadB.start();
    29. threadC.start();
    30. }
    31. public static void main(String[] args) {
    32. //前一行执行下一行才能执行,并不能做到并行执行
    33. new FirstThread().start();//对类进行实例化并调用里面的start方法
    34. }
    35. }

     仔细观察同一秒abc的顺序并不是按照我们启动线程的顺序,他们谁先拿到时间片谁先执行,简单的做到了并发执行。

    注:此方法只是为了演示可行性,实际工作中由于java对于继承的特性我们一边选择接口的方式去完成,也就是下一种方法

    2 Runnable接口

    1. public class SecondThread {
    2. //内部类
    3. class Runner implements Runnable{
    4. @Override
    5. public void run() {
    6. //跑步速度 生成一个随机数
    7. Integer speed = new Random().nextInt(10);
    8. //10秒跑了多少
    9. for(int i = 1;i <= 10;i++){
    10. try {
    11. Thread.sleep(1000);//休眠一秒
    12. } catch (InterruptedException e) {
    13. e.printStackTrace();
    14. }
    15. //Thread.currentThread().getName() 线程类的静态方法.currentThread()获取到当前的线程
    16. System.out.println("第" + i +"秒" +Thread.currentThread().getName() + "跑了:" + i*speed +"米");
    17. }
    18. }
    19. }
    20. public void start(){
    21. Runner runner = new Runner();
    22. Thread threadA = new Thread(runner);//将Runnable对象作为构造参数传入其中
    23. threadA.setName("参赛者A");
    24. Thread threadB = new Thread(new Runner());
    25. threadB.setName("参赛者B");
    26. Thread threadC = new Thread(new Runner());
    27. threadC.setName("参赛者C");
    28. threadA.start();
    29. threadB.start();
    30. threadC.start();
    31. }
    32. public static void main(String[] args) {
    33. //前一行执行下一行才能执行,并不能做到并行执行
    34. new SecondThread().start();//对类进行实例化并调用里面的start方法
    35. }
    36. }

    3 Callable接口

    1. public class ThirdThread {
    2. class Runner implements Callable{//允许线程执行完毕返回值
    3. public String name;
    4. @Override
    5. public Integer call() throws Exception {
    6. //跑步速度 生成一个随机数
    7. Integer speed = new Random().nextInt(10);
    8. //总和
    9. Integer sum = 0;
    10. for(int i = 1;i <= 10;i++){
    11. Thread.sleep(1000);
    12. sum = i * speed;
    13. //this.name指向当前Runner对象的name不是线程的名字
    14. System.out.println("第" + i +"秒" +this.name+ "跑到了:" + sum +"米");
    15. }
    16. return sum;
    17. }
    18. }
    19. public void start() throws ExecutionException, InterruptedException {
    20. ExecutorService executorService = Executors.newFixedThreadPool(3);
    21. Runner threadA = new Runner();
    22. threadA.name="参赛者A";
    23. Runner threadB = new Runner();
    24. threadB.name="参赛者B";
    25. Runner threadC = new Runner();
    26. threadC.name="参赛者C";
    27. //由于语句执行速度快尽管语句有先后顺序还是可以忽略的
    28. Future m1 = executorService.submit(threadA);
    29. Future m2 = executorService.submit(threadB);
    30. Future m3 = executorService.submit(threadC);
    31. executorService.shutdown();//关闭线程池,所有线程结束才关闭
    32. System.out.println(threadA.name + "累计跑了:" + m1.get() + "米");//get的是返回值sum
    33. System.out.println(threadB.name + "累计跑了:" + m2.get() + "米");//get的是返回值sum
    34. System.out.println(threadC.name + "累计跑了:" + m3.get() + "米");//get的是返回值sum
    35. }
    36. public static void main(String[] args) throws ExecutionException, InterruptedException {
    37. new ThirdThread().start();
    38. }
    39. }

    4  小结

    继承Thread, Java对继承不友好,不推荐使用
    实现Runnable接口,Java编程友好,但无法返回执行后数据
    实现Callable接口,可以返回多线程执行结果,编程稍显复杂


    2 线程同步

    现实生活中:


    扔牌游戏:如果我么有一个游戏,谁先把手里的牌扔光谁就是赢家,参与者每个人都一把扔完这样是无序的。但是如果我么通过指定规则,把他设计成一个有序的安排,通过一个小游戏实现把它变得有序,一轮完了以后还有下一轮去选出下一个优胜者,这就是现实中的同步机制。

    代码中:

    synchronized (同步锁)关键字的作用就是利用一个特定的对象设置一个锁lock (赢家),在多线程(参与者)并发访问的时候,同时只允许一个线程(参与者)可以获得这个锁,执行特定的代码(成为赢家)。执行后释放锁,继续由其他线程争抢。


    代码实现

    1. public class Sample {
    2. class Printer{
    3. Object lock = new Object();//创建锁,当有线程获取到锁其他线程会进入到阻塞的状态
    4. public void print() {
    5. synchronized (lock) {
    6. try {
    7. Thread.sleep(500);
    8. System.out.print("111");
    9. Thread.sleep(500);
    10. System.out.print("222");
    11. Thread.sleep(500);
    12. System.out.print("333");
    13. Thread.sleep(500);
    14. System.out.print("444");
    15. System.out.println("");
    16. } catch (Exception e) {
    17. e.printStackTrace();
    18. }
    19. }
    20. }
    21. }
    22. class PrintTask implements Runnable{
    23. public Printer printer;
    24. @Override
    25. public void run() {
    26. printer.print();
    27. }
    28. }
    29. public void start(){
    30. Printer printer = new Printer();
    31. for(int i = 0;i < 10;i++){
    32. PrintTask printTask = new PrintTask();
    33. printTask.printer = printer;
    34. Thread thread = new Thread(printTask);
    35. thread.start();
    36. }
    37. }
    38. public static void main(String[] args) {
    39. Sample sample = new Sample();
    40. sample.start();
    41. }
    42. }

    加锁前

    加锁后 

    如果不加锁输出时多线程同时进行大概率先打印1111 会出现1111 1111 1111 1111 1111 1111 的情况造成了混乱,如果加入锁,我们就能实现线程进入锁后其他线程会阻塞知道上一个线程执行完成,其他线程再去争夺进入锁的机会,就与之前扔牌游戏类似。

    3 synchronized的锁对象


    synchronized代码块 -任意对象即可
    synchronized方法 - this当前对象
    synchronized静态方法-该类的字节码对象

    4 线程安全的产生及解决方式

    在拥有共享数据的多条线程并行执行的程序中,线程安全的代码会通过同步机制保证各个线程都可以正常且正确的执行,不会出现数据污染等意外情况。

    实例,杜绝电商秒杀活动中“超卖”现象。

    新建一个包 包下有三个类

    Consumer:

    1. //消费者类
    2. class Consumer implements Runnable{
    3. //所有消费者都来到同一个商城
    4. public Mall mall;
    5. @Override
    6. public void run() {
    7. //商城为每一名消费者销售商品
    8. mall.sale();
    9. }
    10. }

     Mall:

    1. //模拟商城销售商品
    2. public class Mall {
    3. //消费者调用synchronized
    4. public void sale(){
    5. //检验库存
    6. if(Stock.count > 0 ){
    7. try {
    8. //模拟商城办理销售业务,用时5毫秒
    9. Thread.sleep(5);
    10. } catch (InterruptedException e) {
    11. e.printStackTrace();
    12. }
    13. //销售成功库存减少
    14. Stock.count--;
    15. System.out.println("商品销售成功");
    16. }else{
    17. System.out.println("商品库存不足,请下次再来吧!");
    18. }
    19. }
    20. public static void main(String[] args) {
    21. //实例化唯一的商城对象
    22. Mall mall = new Mall();
    23. //模拟5名顾客同时涌入商城购买商品,库存仅3
    24. for(int i = 0 ; i < 10 ; i++){
    25. Consumer consumer = new Consumer();
    26. consumer.mall = mall;//将实例化的mall赋值给consumer.mall
    27. Thread thread = new Thread(consumer);
    28. thread.start();
    29. }
    30. try {
    31. //模拟库存清点
    32. Thread.sleep(1000);
    33. System.out.println("当前商品库存为:" + Stock.count);
    34. } catch (InterruptedException e) {
    35. e.printStackTrace();
    36. }
    37. }
    38. }

     Stock:

    1. //库存类
    2. public class Stock {
    3. //当前商品库存剩余3个
    4. public static int count = 3;
    5. }

    如果不加锁就会出现超卖现象:

    如果加上锁,实质就是方法上加入synchroized

    1. //消费者调用
    2. public synchronized void sale(){
    3. //检验库存
    4. if(Stock.count > 0 ){
    5. try {
    6. //模拟商城办理销售业务,用时5毫秒
    7. Thread.sleep(5);
    8. } catch (InterruptedException e) {
    9. e.printStackTrace();
    10. }
    11. //销售成功库存减少
    12. Stock.count--;
    13. System.out.println("商品销售成功");
    14. }else{
    15. System.out.println("商品库存不足,请下次再来吧!");
    16. }
    17. }

  • 相关阅读:
    【VR】Network Manager HUD
    https
    40 JAVA安全-JWT安全及预编译CASE注入等
    开放 LLM 排行榜: 深入研究 DROP
    AWS云服务器EC2实例实现ByConity快速部署
    【MySQL】外连接(左外连和右外连)和主键,mysql约束
    【微服务专题】Nacos详解
    Github操作—SSH免密登录(六)——Git
    间隔连续问题
    Excel中的宏、VBA
  • 原文地址:https://blog.csdn.net/weixin_57169969/article/details/126723043