多线程讲解(详解)

目录

什么是多线程?

为什么要使用多线程?

线程的创建

使用Thread实现

从以上代码我们梳理一下多线程创建步骤:

注意:

小示例

首先,引入依赖

然后,按照我们刚刚说的构建多线程的步骤进行构建,并实现一个下载功能

接下来在run方法中调用图片下载功能

最后在主函数中调用

执行结果

Thread类的相关方法

使用Runnable实现

我们直接看代码

[​编辑 那我们同样的来总结一下步骤](#编辑 那我们同样的来总结一下步骤)

那到底使用哪个方法来实现比较好呢?我们可以来看一下对比

继承Thread类

实现Runnable接口

线程实例(引出的并发问题)

抢票问题

线程同步

那接下来我们再看一个案例,银行取钱的问题


接下来我将向各位介绍线程的相关知识,请各位上车,我们马上就要开始啦~

什么是多线程?

说起多线程,那就不得不说什么是进程了,进程是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。在早期面向进程设计的计算机结构中,进程是程序的基本执行实体;在当代面向线程设计的计算机结构中,进程是线程的容器, 因此一个进程当中就可能存在多个线程。那么多线程就很容易理解:多线程就是指一个进程中同时有多个执行路径(线程)正在执行

为什么要使用多线程?

我们学多线程,为什么要学呢?多线程有什么好的地方需要我们去学习呢?这里就不得不说说多线程的优点了:

  • 在我们的程序中,有很多的操作是非常耗时的,就比如数据库读写操作、文件IO操作等,如果我们把这些都做成单线程,无疑整个程序就必须等到这些执行完之后才能执行之后的操作,所以如果我们使用多线程那我们就可以把这些程序放到后台执行的同时,执行其他操作。
  • 提高了整个程序的效率。
  • 对于一些用户输入、文件存储等,多线程就有了很好的实践。

当然,任何东西都是有他的缺点的,那多线程的缺点又是什么呢?

  • 使用太多线程,是很耗系统资源,因为线程需要开辟内存。更多线程需要更多内存。
  • 影响系统性能,因为操作系统需要在线程之间来回切换。
  • 需要考虑线程操作对程序的影响,如线程挂起,中止等操作对程序的影响。
  • 线程使用不当会发生很多问题。

线程的创建

线程的创建主要包括两种方法,一种是继承Thread,重写run方法,另一种是实现Runable接口,也需要重写run方法。

线程的启动,调用start()方法即可。 我们也可以直接使用线程对象的run方法,不过直接使用,run方法就只是一个普通的方法了。

接下来我们一一进行讲解~

使用Thread实现

java 复制代码
public class testThread extends Thread{

    @Override
    public void run() {
//        run方法线程体
        for (int i = 0; i < 30; i++) {
            System.out.println("这是啥????????"+i);
        }
    }

    public static void main(String[] args) {
//        main线程,主线程
//        创建一个线程对象
        testThread testThread=new testThread();
//        调用start方法开启线程
//        该方法可以同时并发执行多个线程
        testThread.start();
            System.out.println(Thread.currentThread().getName()+":这是主线程");
    }
}

结果如下:

输出太多了,我这里就没有截完~

从以上代码我们梳理一下多线程创建步骤:
  1. 创建一个类,继承Thread类
  2. 重写run()方法
  3. 在主函数中使用start()方法来执行多线程

接下来我们再稍微修改一下代码

java 复制代码
public class testThread extends Thread{

    @Override
    public void run() {
//        run方法线程体
        for (int i = 0; i < 30; i++) {
            System.out.println("这是啥????????"+i);
        }
    }

    public static void main(String[] args) {
//        main线程,主线程
//        创建一个线程对象
        testThread testThread=new testThread();
//        调用start方法开启线程
//        该方法可以同时并发执行多个线程
        testThread.start();
        for (int i = 0; i < 50; i++) {
            System.out.println("这是主线程"+i);
        }
//            System.out.println(Thread.currentThread().getName()+":这是主线程");
    }
}

部分结果:

从上面的结果我们看到,主线程中的方法和run中的方法并不是有秩序的执行,而是交互执行,所以我们这里总结特点,run方法由jvm调度,什么时候调度,执行的过程控制都有操作系统的CPU调度决定。

注意:
  • 如果自己手动调用run()方法,那么就只是普通方法,没有启动多线程模式。
  • 想要启动多线程,必须调用start方法。
  • 一个线程对象只能调用一次start()方法启动,如果重复调用了,则将抛出以上 的异常"IllegalThreadStateException"。
小示例

接下来我们用一个小示例来充分体会一下多线程的特点(这里做一个图片下载的功能)~

首先,引入依赖
XML 复制代码
      <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.7</version>
        </dependency>
然后,按照我们刚刚说的构建多线程的步骤进行构建,并实现一个下载功能
java 复制代码
   public void  downloadPicture(String url, String name) {
            try{
                FileUtils.copyURLToFile(new URL(url),new File(name));
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("图片"+name+"下载失败");
            }

        }
接下来在run方法中调用图片下载功能
java 复制代码
 public void run() {
        DownloadPicture downloadPicture=new DownloadPicture();
        downloadPicture.downloadPicture(url, name);
        System.out.println("下载了文件名为"+name);
    }
最后在主函数中调用
java 复制代码
 public static void main(String[] args) {
        testThreadWithDownloadPicture t1 = new testThreadWithDownloadPicture("https://gd-hbimg.huaban.com/8ddcc487e510962d0aff6f296025483a26ed4b2f106ce2f-1QFFia_fw658webp","1.jpg");
        testThreadWithDownloadPicture t2 = new testThreadWithDownloadPicture("https://gd-hbimg.huaban.com/8ddcc487e510962d0aff6f296025483a26ed4b2f106ce2f-1QFFia_fw658webp","2.jpg");
        testThreadWithDownloadPicture t3 = new testThreadWithDownloadPicture("https://gd-hbimg.huaban.com/8ddcc487e510962d0aff6f296025483a26ed4b2f106ce2f-1QFFia_fw658webp","3.jpg");

        t1.start();
        t2.start();
        t3.start();
    }
执行结果

你可以运行多次,你会发现每次输出的顺序都不一样~

Thread类的相关方法

  • start():启动当前线程;调用当前线程的run()方法
  • run(): 通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
  • currentThread():静态方法,返回执行当前代码的线程
  • getName():获取当前线程的名字
  • setName():设置当前线程的名字
  • yield():暂停当前正在执行的线程,把执行机会让给优先级相同或更高的线程,若没有,继续执行当前线程。
  • join():在线程a中调用线程b的join(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞状态。
  • stop():已过时。当执行此方法时,强制结束当前线程,不推荐使用。
  • sleep(long millitime):让当前线程"睡眠"指定的millitime毫秒。在指定的millitime毫秒时间内,当前线程是阻塞状态。
  • isAlive():判断当前线程是否存活

使用Runnable实现

我们直接看代码
java 复制代码
public class testRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("今天星期几~"+i);
        }
    }

    public static void main(String[] args) {
        testRunnable testRunnable=new testRunnable();
        new Thread(testRunnable).start();
        for (int i = 0; i < 50; i++) {
            System.out.println("这里是主线程--"+i);
        }
    }
}

部分结果

那我们同样的来总结一下步骤
  1. 创建一个类,实现Runnable这个接口
  2. 重写run方法
  3. 在主函数中使用new Thread().start();的方法调用run方法

我们发现,其实以上两种方法的实现步骤都差不多,这里你可以试试使用Runnable方法来修改我们刚刚的下载图片的案例~

这里我们只需要修改主函数中的方法,其余地方均不做修改

java 复制代码
 public static void main(String[] args) {
        testThreadWithDownloadPicture t1 = new testThreadWithDownloadPicture("https://gd-hbimg.huaban.com/8ddcc487e510962d0aff6f296025483a26ed4b2f106ce2f-1QFFia_fw658webp","1.jpg");
        testThreadWithDownloadPicture t2 = new testThreadWithDownloadPicture("https://gd-hbimg.huaban.com/8ddcc487e510962d0aff6f296025483a26ed4b2f106ce2f-1QFFia_fw658webp","2.jpg");
        testThreadWithDownloadPicture t3 = new testThreadWithDownloadPicture("https://gd-hbimg.huaban.com/8ddcc487e510962d0aff6f296025483a26ed4b2f106ce2f-1QFFia_fw658webp","3.jpg");

//        t1.start();
//        t2.start();
//        t3.start();

        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }

同样也能得到结果~

那到底使用哪个方法来实现比较好呢?我们可以来看一下对比

继承Thread类

  • 子类继承Thread类具备多线程能力
  • 启动线程:子类对象. start()
  • 不建议使用:避免OOP单继承局限性

实现Runnable接口

  • 实现接口Runnable具有多线程能力
  • 启动线程:传入目标对象+Thread对象.start()
  • 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用

线程实例(引出的并发问题)

既然我们讲完了如何创建多线程,那练手肯定是必要的,这里我们就来看一个比较经典的案例

抢票问题

乘坐高铁都需要进行抢票,如何用多线程进行实现呢?

java 复制代码
public class testGaotieSoldTicket implements Runnable{

    private Integer ticketNum = 10;
    @Override
    public void run() {
        while (ticketNum > 0) {
            System.out.println(Thread.currentThread().getName() + "--->售出第" + ticketNum + "张票");
            ticketNum--;
        }
    }

    public static void main(String[] args) {
        testGaotieSoldTicket gts = new testGaotieSoldTicket();
        //创建三个线程
        new Thread(gts,"售票窗口1").start();
        new Thread(gts,"售票窗口2").start();
        new Thread(gts,"售票窗口3").start();
    }
}

结果

看到以上结果了吗,有没有发现什么问题?没错,出现了对同一张票进行了多次出售的情况,怎么做呢?此时我们需要使用并发来控制

注:如果你的输出结果始终是统一线程的输出,你可以使用Thread.sleep()来模拟延时

线程同步

处理多线程问题时,多个线程访问同一个对象﹐并且某些线程还想修改这个对象﹒这时候我们就需要线程同步﹒线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。

由于同一进程的多个线程共享同一块存储空间﹐在带来方便的同时,也带来了访问冲突问题﹐为了保证数据在方法中被访问时的正确性﹐在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源﹐其他线程必须等待,使用后释放锁即可.存在以下问题:

  • 一个线程持有锁会导致其他所有需要此锁的线程挂起;
  • 在多线程竞争下,加锁﹐释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
  • 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置﹐引起性能问题﹒

所以结合我们的理解,我们对刚刚的抢票问题进行修改

java 复制代码
public class testGaotieSoldTicket implements Runnable{

    private Integer ticketNum = 10;

    private Boolean flag=true;
    @Override
    public void run() {
        while(flag){
            soldTicket();
        }
    }

    public static void main(String[] args) {
        testGaotieSoldTicket gts = new testGaotieSoldTicket();
        //创建三个线程
        new Thread(gts,"售票窗口1").start();
        new Thread(gts,"售票窗口2").start();
        new Thread(gts,"售票窗口3").start();
    }

    public synchronized void soldTicket(){
        while (ticketNum > 0) {
            try {
//                延时
                Thread.sleep(300);
                System.out.println(Thread.currentThread().getName() + "--->售出第" + ticketNum + "张票");
                ticketNum--;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        flag=false;
    }
}

从上面的结果我们可以看到,没有出现重复取票的行为,因为我们已经在售票的方法前加上了synchronized,对每一次购票行为都加上了锁。

那接下来我们再看一个案例,银行取钱的问题

java 复制代码
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "结婚基金");
        Thread you = new Thread(new Drawing(account, 50, "你"));
        Thread girlFriend = new Thread(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() {
    
        // 判断是否有钱
        if (account.money - drawingMoney < 0) {
            System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
            return;
        }

        // sleep 放大问题的发生性
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 卡内的钱 = 余额 - 取的钱
        account.money = account.money - drawingMoney;
        // 你手上的钱
        nowMoney = nowMoney + drawingMoney;
        System.out.println(account.name + "余额为:" + account.money);
        // this.getName = Thread.currentThread().getName()
        System.out.println(this.getName() + "手里的钱为:" + nowMoney);
    }
}

输出结果就不给出了,由于没有做同步这里的输出结果可能会误导你们以为这段代码是错误~

那接下来我们给这段代码加上锁(要明白在哪儿加上锁,即当前程序对什么进行增删改查操作,以这个案例为例,对account进行处理,所以我们对acount加锁,而不是银行)

java 复制代码
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "结婚基金");
        Thread you = new Thread(new Drawing(account, 50, "你"));
        Thread girlFriend = new Thread(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;
            }

            // sleep 放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 卡内的钱 = 余额 - 取的钱
            account.money = account.money - drawingMoney;
            // 你手上的钱
            nowMoney = nowMoney + drawingMoney;
            System.out.println(account.name + "余额为:" + account.money);
            // this.getName = Thread.currentThread().getName()
            System.out.println(this.getName() + "手里的钱为:" + nowMoney);
        }
    }
}

好了,以上就是全部内容了,重点理解一下synchronized在哪儿进行加锁,要不然加错了是不能起到同步作用的~

相关推荐
alim20127 分钟前
python语句性能分析
开发语言·python
未来可期,静待花开~10 分钟前
C++基础(八):类和对象 (下)
开发语言·jvm·c++
2402_8575893615 分钟前
sklearn模型评估全景:指标详解与应用实例
开发语言·人工智能·scala
GISer_Jing16 分钟前
Javascript常见数据结构和设计模式
开发语言·javascript·数据结构
真果粒wrdms25 分钟前
【SQLite3】常用API
linux·服务器·c语言·jvm·数据库·oracle·sqlite
yukai0800835 分钟前
Python一些可能用的到的函数系列130 UCS-Time Brick
开发语言·python
伏颜.35 分钟前
Spring懒加载Bean机制
java·spring
细心的莽夫36 分钟前
集合复习(java)
java·开发语言·笔记·学习·java-ee
卫卫周大胖;39 分钟前
【C++】多态(详解)
开发语言·c++
yours_Gabriel42 分钟前
java基础:面向对象(二)
java·开发语言·笔记·学习