【多线程基础】创建线程的五种方式、实现多线程数组求和

Hi~!这里是奋斗的明志,很荣幸您能阅读我的文章,诚请评论指点,欢迎欢迎 ~~
🌱🌱个人主页:奋斗的明志
🌱🌱所属专栏:Java多线程

📚本系列文章为个人学习笔记,在这里撰写成文一为巩固知识,二为展示我的学习过程及理解。文笔、排版拙劣,望见谅。

在这里插入图片描述

在这里插入图片描述

前言

  • 多线程代码
  • 线程,本身是操作系统提供的
  • 操作系统提供了 API 让我们操作线程
  • JVM 就对 操作系统 API 进行了封装
  • 线程这里,提供了 Thread类,表示线程

一、第一个多线程程序

感受多线程和普通线程的区别:

  • 每个线程都是一个独立的执行流
  • 多线程之间是“并发”执行的
import java.util.Random;

public class Test02 {
    private static class MyThread extends Thread{
        @Override
        public void run() {
            Random random = new Random();
            while (true){
                //打印线程名称
                System.out.println(Thread.currentThread().getName());
                try {
                    //随机停止 0 - 9 秒
                    Thread.sleep(random.nextInt(10));
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();

        Random random = new Random();
        while (true){
            //打印线程名称
            System.out.println(Thread.currentThread().getName());
            try {
                //随机停止 0 - 9 秒
                Thread.sleep(random.nextInt(10));
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

接下来看运行结果

在这里插入图片描述

二、使用 jconsole 命令观察线程

能够更清晰看到内部结构

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

三、创建线程的五种写法

@Override注解,相当于是提示编译器,进行更严格的检查。

1.继承 Thread 类

  • 继承 Thread 来创建⼀个线程类
class MyThread extends Thread{
    @Override
    public void run() {
        while (true){
            System.out.println("hello thread");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
  • 创建 MyThread 类的实例
Thread t = new MyThread();
  • 调⽤ start 方法启动线程
t.start();

run方法只是描述了线程要干啥任务

t.start() 调用 操作系统 提供的 “创建线程” api
在内核中创建对应的 pcb ,并把pcb 加入到链表中
进一步的系统调度到这个线程之后,就会执行上述 run 方法中的逻辑

2.实现 Runnable 接口

package thread;

class MyRunnable implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("这里是自己创建的线程的代码");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

public class Demo2 {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
        while (true){
            System.out.println("hello main");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

上述代码其实有两个线程:
t 线程
main 方法所在的线程(主线程)

在这里插入图片描述


每一秒进行打印的时候,可能 main 在前面,也有可能 自己创建的线程在前面
由此可以看出多个线程的调度顺序,是“无序”的
在操作系统内部也称为“抢占式执行”

3.继承 Thread, 重写 run, 使用匿名内部类

package thread;

public class Demo3 {
    public static void main(String[] args) {
        Thread t = new Thread(){
            @Override
            public void run() {
                while (true){
                    System.out.println("Thread - 0");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };

        t.start();
        while (true){
            System.out.println("hello main");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

4.实现 Runnable, 重写 run, 使用匿名内部类

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("Thread - 0");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

        t.start();
        while (true){
            System.out.println("hello main");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

在这里插入图片描述

5.使用 lambda 表达式

package thread;

public class Demo5 {
    public static void main(String[] args) {
        //比较推荐的写法,匿名内部类的平替
        Thread t = new Thread( () -> {
            while (true){
                System.out.println("Thread - 0");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"我的线程");

        t.start();
        while (true){
            System.out.println("hello main");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

在这里插入图片描述

上述五种写法,本质都是
要把线程执行的任务表示出来
通过 Thread 的 start 来创建/启动系统中的线程
Thread 对象和操作系统内核中的线程是一一对应的关系

四、实现多线程数组求和

  1. 给定一个很长的数组 (长度 1000w), 通过随机数的方式生成 1-100 之间的整数.
  2. 实现代码, 能够创建两个线程, 对这个数组的所有元素求和.
  3. 其中线程1 计算偶数下标元素的和, 线程2 计算奇数下标元素的和.
  4. 最终再汇总两个和, 进行相加
  5. 记录程序的执行时间.
import java.util.Random;

public class Test03 {
    private static final int ARRAY_SIZE = 1000_0000;
    private static final int MAX_VALUE = 100;

    public static void main(String[] args) throws InterruptedException {
        //记录开始的时间
        long start = System.currentTimeMillis();
        //1.给定一个很长的数组(长度为1000w),通过随机数的方式生成 1-100 之间的整数
        int[] array = new int[ARRAY_SIZE];
        //生成随机数,对数组进行填充
        Random random = new Random();
        for (int i = 0; i < ARRAY_SIZE; i++) {
            array[i] = random.nextInt(MAX_VALUE) + 1;
        }


        //2.创建两个线程 对数组内的元素进行求和
        //3.线程一计算偶数下标元素的和,线程二计算奇数下标元素的和

        //实例化操作类
        SumOperator operator = new SumOperator();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < ARRAY_SIZE; i += 2) {
                operator.addEvenSum(array[i]);
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 1; i < ARRAY_SIZE; i += 2) {
                operator.addOddSum(array[i]);
            }
        });

        //启动线程
        t1.start();
        t2.start();

        //等待线程结束
        t1.join();
        t2.join();

        //记录结束时间
        long end = System.currentTimeMillis();
        System.out.println("计算结果为:" + operator.result());
        System.out.println("总耗时:" + (end - start) + "ms.");
    }
}

class SumOperator{
    long evenSum;//偶数和
    long oddSum;//奇数和

    public void addEvenSum(int num){
        evenSum += num;
    }
    public void addOddSum(int num){
        oddSum += num;
    }
    public long result() {
        System.out.println("偶数和:" + evenSum);
        System.out.println("奇数和:" + oddSum);
        return evenSum + oddSum;
    }
}


在这里插入图片描述


五、利用循环创建多个线程

  • 在子线程执行完毕后再执行主线程代码

  • 有20个线程,需要同时启动。

  • 每个线程按0-19的序号打印,如第一个线程需要打印0

  • 请设计代码,在main主线程中,等待所有子线程执行完后,再打印 ok

public class Test05 {
    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[20];
        for (int i = 0; i < 20; i++) {
            final int n = i;
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {//内部类使用外部的变量,必须是final修饰
                    System.out.println(n);
                }
            });
        }
        for (Thread t : threads) {
            t.start();
        }
        for (Thread t : threads) {//同时执行20个线程,再等待所有线程执行完毕
            t.join();
        }
        System.out.println("OK");
    }
}

在这里插入图片描述


六、Thread类中run和start的区别

  • 作用功能不同:

run方法的作用是描述线程具体要执行的任务;
start方法的作用是真正的去申请系统线程

  • 运行结果不同:

run方法是一个类中的普通方法,主动调用和调用普通方法一样,会顺序执行一次;
start调用方法后, start方法内部会调用Java 本地方法(封装了对系统底层的调用)真正的启动线程,并执行run方法中的代码,run 方法执行完成后线程进入销毁阶段。

总结

【注意点一】

try - catch:
在实际开发中,里面的内容应该是自己实现的。
例如:

  • 可能会打印一些日志,把出现的异常情况都记录在日志文件中
  • 触发一些重试类的操作
  • 触发一些“回滚”类的操作
  • 触发一些报警机制(给程序员发短信…)

【注意点二】

在main方法中 处理 sleep 既可以使用 throws,也可以使用 try - catch
在线程 run 方法中,只能使用 try - catch
与方法签名有关


【注意点三】

未来实际开发中,发现你负责的服务器程序,消耗 CPU 资源超出预期,应该如何排查这个问题?

  • 首先要先确认,是哪个线程消耗的 CPU 比较高
  • 未来会涉及到一些第三方工具,可以看到每个线程 CPU 消耗情况
  • 确定之后,进一步排查,线程中是否有 “ 非常快速 ” 的循环

在这里插入图片描述

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值