JavaEE初阶---多线程(初阶)

一 : 学习目标

  • 认识多线程
  • 掌握多线程程序的编写
  • 掌握多线程的状态
  • 掌握什么是线程不安全及解决思路
  • 掌握synchronized、volatile关键字

二 : 初识线程

2.1 线程概念

线程(thread)是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务.

在计算机中 , 为了充分利用CPU的多核资源 , 我们引入了并发编程 . 使用多进程这种编程模型 , 完全可以做到并发编程 , 且能够使CPU多核被充分利用 .但有些场景下 , 需要频繁地创建/销毁进程 , 此时就比较低效 .

例如我们写一个服务器程序 , 需要在同一时间给多个客户端提供服务 , 此时就需要用到并发编程了 . 典型做法是给每个客户端分配一个进程 , 提供一对一的服务 . 但是创建/销毁进程 , 本身就是一个比较低效的操作 . 需要经过多个步骤 :

1.创建PCB ;
2.分配系统资源 ;
3.把PCB加入到内核的双向链表中 .

其中 , 分配系统资源需要在系统内核资源管理模块 , 进行一次遍历操作 .

为了提高这个场景下的效率 , 就引入了"线程" (线程又叫"轻量级进程") .

在这里插入图片描述

进程是线程的容器 . 一个进程里,通常包含多个线程 .

每个线程其实也有自己的PCB,一个进程里可能就对应多个PCB .

同一个进程里的多个线程之间 , 共用同一份系统资源 . 这就意味着 , 创建新线程 , 不需要重新给他分配系统资源 , 只需要复用之前的即可 . 因此 , 创建线程只需要 :

1.创建PCB ;
2.把PCB加入到内核的双向链表中 .

在这里插入图片描述

2.2 进程和线程之间的区别

Q : 进程和线程之间的区别 ?

A :

  1. 进程是包含线程的 , 线程是在进程内部的 ;
  2. 每个进程有独立的虚拟地址空间(进程之间的资源是独立的) , 也有自己独立的文件描述符表 ; 同一个进程的多个线程之间 , 则共用这一份虚拟地址空间和文件描述符表 .
  3. 进程是操作系统中资源分配的基本单位 , 线程是操作系统中调度执行的基本单位 .
  4. 多个进程同时执行的时候 , 如果一个进程挂了 , 一般不会影响的别的进程 . 同一个进程内的多个线程之间 , 如果一个线程挂了 , 很可能会把整个进程带走 , 其他同进程中的线程也就没了 .

2.3 Java的线程和操作系统线程的关系

线程是操作系统中的概念 . 操作系统内核实现了线程这样的机制, 并且对用户层提供了一些 API 供用户使用(例如 Linux 的 pthread 库).

Java 标准库中 Thread 类可以视为是对操作系统提供的 API 进行了进一步的抽象和封装 .

Thread实例是java中对于线程的表示,实际上想要真正跑起来,还需要操作系统里面的线程!创建好Thread,此时系统里面还没有线程 .直到调用start方法,操作系统才真的创建了线程,并进行执行 .

操作系统创建线程的步骤:

1.创建PCB;

2.把PCB加入到链表里~

2.4 线程优点

1.线程的优点

  1. 创建一个新线程的代价要比创建一个新进程小的多;
  2. 与进程之间的切换相比 , 线程之间的切换需要操作系统做的工作要少得多;
  3. 线程占用的资源要比进程少得多;
  4. 能够充分利用多处理器的可并行数量;
  5. 在等待慢速I/O操作结束的同时 , 程序可以执行其他的计算任务;
  6. 计算密集型应用,为能在多处理器上运行 , 将计算分解到多个线程中实现;
  7. I/O密集型应用,为了提高性能,将I/O操作重叠 , 线程可以同时等待不同的I/O操作.

在这里插入图片描述

2.实例1

在这里插入图片描述
在这里插入图片描述中
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

此时还涉及线程安全问题 .

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.实例2

(建议了解本文三 , 四两节内容后回看这部分示例)

能够更充分的利用CPU的多核资源.
package Thread;

public class Demo6 {
   
    // 1. 单个线程, 串行的, 完成 20 亿次自增.
    // 2. 两个线程, 并发的, 完成 20 亿次自增.
    private static final long COUNT = 20_0000_0000;

    private static void serial() {
   
        // 需要把方法执行的时间给记录下来.
        // 记录当前的毫秒级时间戳.
        long beg = System.currentTimeMillis();

        int a = 0;
        for (long i = 0; i < COUNT; i++) {
   
            a++;
        }
        a = 0;
        for (long i = 0; i < COUNT; i++) {
   
            a++;
        }

        long end = System.currentTimeMillis();
        System.out.println("单线程消耗的时间: " + (end - beg) + " ms");
    }

    private static void concurrency() {
   
        long beg = System.currentTimeMillis();

        Thread t1 = new Thread(() -> {
   
            int a = 0;
            for (long i = 0; i < COUNT; i++) {
   
                a++;
            }
        });

        Thread t2 = new Thread(() -> {
   
            int a = 0;
            for (long i = 0; i < COUNT; i++) {
   
                a++;
            }
        });

        t1.start();
        t2.start();

        try {
   
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println("并发执行的时间: " + (end - beg) + " ms");
    }

    public static void main(String[] args) {
   
        serial();
        concurrency();
    }
}

在这里插入图片描述
在这里插入图片描述

分析 :

在这里插入图片描述
在这里插入图片描述

4.join用法

线程之间的执行顺序是完全随机的,看系统的调度!join就是一种确定线程执行顺序的辅助手段!!通过joni可以控制两个线程的结束顺序!!!!但是线程的开始执行顺序是无法确定的!!!

在这里插入图片描述

示例一 : t2线程等待t1线程结束 , main线程等待t2线程结束 .

package Thread;

public class Demo11 {
   
    private static Thread t1 = null;
    private static Thread t2 = null;

    public static void main(String[] args) throws InterruptedException {
   
        System.out.println("main begin");
        t1 = new Thread(()->{
   
            System.out.println("t1 begin");
            try {
   
                Thread.sleep(5000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
            System.out.println("t1 end");
        });
        t1.start();

        t2 = new Thread(()->{
   
            System.out.println("t2 begin");
            try {
   
                t1.join();
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
            System.out.println("t2 end");
        });
        t2.start();

        t2.join();
        System.out.println("main end");
    }
}

在这里插入图片描述

示例二 : main线程运行t1 和1t2 , t1和t2随机调度 .

package Thread;

//控制main线运行t1,t1执行完再执行t2
public class Demo12 {
   
    public static void main(String[] args) throws InterruptedException {
   
        System.out.println("main begin");
        Thread t1 = new Thread(()->{
   
            System.out.println("t1 begin");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
            System.out.println("t1 end");
        });
        t1.start();


        Thread t2 = new Thread(()->{
   
            System.out.println("t2 begin");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
            System.out.println("t2 end");
        });
        t2.start();
        
        t1.join();
        t2.join();
        System.out.println("main end");
    }

}

在这里插入图片描述
在这里插入图片描述

join还有一个带参数的版本 :

在这里插入图片描述
未来开发实际程序的时候 , 像这样的等待操作,一般都不会使用死等的方式 . 死等的方式有风险!!万一代码出了bug 没控制好,死等就容易让服务器"卡死”,无法继续工作.因为一个小问题就影响到全局 .

更多的是要等待的时候预期好最多等多久 , 如果时间到了还没有等来,就要做出一些措施!!

总结join的行为 :

  1. 如果被等待的线程还没执行完,就阻塞等待;
  2. 如果被等待的线程已经执行完了,就直接返回 .

2.5 多线程的应用场景

在这里插入图片描述

比如排核酸时候 , 排队的过程就是等待 , 类似于等待IO结束 , 此时同学们就打开青年大学习 , 顺便学一手 , 学习新思想 , 争做新青年 !!!

在这里插入图片描述
在这里插入图片描述

三 :第一个多线程程序

在这里插入图片描述

package Thread;

class MyThread1 extends Thread {
   
    @Override
    public void run() {
   
        while (true) {
   
            System.out.println("hello thread!");
            }
        }
    }


public class Demo0 {
   
    public static void main(String[] args) {
   
        Thread t = new MyThread1();  //向上转型的写法
        t.start();
        while(true){
   
            System.out.println("hello main!");
        }
    }
}

在这里插入图片描述

四 : 创建线程的五种方法

4.1 方法一

创建一个类继承Thread,重写run方法.这种写法,线程和任务内容是绑定在一起的.
package Thread;

class MyThread extends Thread {
   
    @Override
    public void run() {
   
        while (true) {
   
            System.out.println("hello thread!");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
        }
    }
}


public class Demo1 {
   
    public static void main(String[] args) {
   
        // 创建一个线程
        // Java 中创建线程, 离不开一个关键的类, Thread
        // 一种比较朴素的创建线程的方式, 是写一个子类, 继承 Thread, 重写其中的 run 方法.
        Thread t = new MyThread();
        t.start();

        while(true){
   
            System.out.println("hello Thread!");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

关于打印顺序 : 默认情况下,多个线程的执行顺序是随机的,是“无序”的,是随机调度的!

如何查看当前进程里的线程 ?

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

关于sleep()方法

在这里插入图片描述

为什么要捕获InterruptedException异常 ?

sleep(1000)就是要休眠1000ms , 但在休眠过程中 , 可能有一些意外 , 把这个线程提前唤醒了 , 此时就会触发这个终端异常 !

run和start的区别 ?

package Thread;

class MyThread extends Thread {
   
    @Override
    public void run() {
   
        while (true) {
   
            System.out.println("hello thread!");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
        }
    }
}


public class Demo1 {
   
    public static void main(String[] args) {
   
        Thread t = new MyThread();  //向上转型的写法
          //t.start();
          t.run();
        while(true){
   
            System.out.println("hello main!");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述
这时候没有打印hello main了 . 这说明 , run方法和start方法是有本质区别的 :

简单说,直接调用run方法,没有创建新的线程,而只是在之前的线程中,执行了run里面的内容.

使用start方法,则是创建新的线程,新的线程里面会调用run,新线程和旧线程之间是并发执行的关系.

详细总结 :

在这里插入图片描述

4.2 方法二

创建一个类,实现Runnable接口,重写run.
package Thread;

class MyRunnable implements Runnable{
   
    @Override
    public void run() {
   
        while (true){
   
            System.out.println("hello thread!");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
        }
    }
}

public class Demo2 {
   
        public static void main(String[] args) {
   
            //创建线程
            Runnable runnable = new MyRunnable();
            Thread t = new Thread(runnable);
            t.start();

            while (true) {
   
                System.out.println("hello main!");
                try {
   
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
   
                    e.printStackTrace();
                }
        }
    }
}

在这里插入图片描述

在这里插入图片描述

代码要求 : “高内聚,低耦合” .

在这里插入图片描述

4.3 方法三

仍使用继承Thread类,但是不再显式继承,而是使用"匿名内部类" .
package Thread;

public class Demo3 {
   
    public static void main(String[] args) {
   
        Thread t = new Thread(){
   
            @Override
            public void run(){
   
                while(true){
   
                    System.out.println("hello thread!");
                    try {
   
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
   
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();
        while(true){
   
            System.out.println("hello main!");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
        }
    }

}

在这里插入图片描述

4.4 方法四

Runnable接口 + 匿名内部类
package Thread;

public class Demo4 {
   
    public static void main(String[] args) {
   
        Thread t = new Thread(new Runnable() {
   
            @Override
            public void run() {
   
                while (true){
   
                    System.out.println("hello thread!");
                    try {
   
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
   
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
        while(true){
   
            System.out.println("hello main!");
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

4.5 方法五

使用lambda表达式定义任务(推荐做法)
package Thread;

public class Demo5 {
   
    public static void main(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值