java 线程基础

java 线程基础

1.线程相关概念

  • 线程由进程创建 是进程的一个实体

  • 一个进程可以拥有多个线程

  • 单线程:同一个时刻 只允许执行一个线程

  • 多线程:同一个时刻 可以执行多个线程

  • 并发:在同一个时刻 多个任务交替执行 造成一种“貌似同时”的错觉 简而言之 单核CPU实现的多任务就是并发

    另一种描述(出自计算机操作xi’t):并发是指两个或多个事件在同一时间间隔内发生

  • 并行: 同一个时刻 多个任务同时执行 多个任务之间互不干扰的同时执行 例如:多核CPU可以实现并行

  • 并发和并行区别是什么

  • 查看当前电脑CPU个数的Java程序

    public class DemoTest {
         
         
        public static void main(String[] args) {
         
         
            Runtime runtime = Runtime.getRuntime();
            int i = runtime.availableProcessors();
            System.out.println("当前电脑CPU数量:"+i);
        }
    }
    

2.线程基本使用

  • 创建线程的两种方式:

    1. 继承Thread类 重写run方法
    • 当一个类(自己的类) 继承Thread类 该类就可以当作线程使用

    • 并且我们要重写Thread类的run方法 写上自己的业务逻辑

    • run Thread类 实现了Runnable接口的run方法

    • 样例代码:

    public class DemoTest {
         
         
        public static void main(String[] args) throws InterruptedException {
         
         
            /*创建Myth对象 可以当作进程使用*/
            Myth myThread = new Myth();
            myThread.start();//启动线程
    	
            /*说明:当main线程启动一个子线程 Thread-0 主线程不会阻塞 会继续执行*/
    
            System.out.println("主线程继续执行:"+Thread.currentThread().getName());
            for (int i = 0; i < 60; i++) {
         
         
                System.out.println("主线程 i="+i);
                /*主线程休眠1s*/
                Thread.sleep(1000);
            }
        }
    }
    
    class Myth extends Thread {
         
         
        int times=1;
        @Override
        public void run() {
         
         
    
            while (true) {
         
         
                /*创建一个线程 每隔1s 在控制台输出*/
                System.out.println(times+"我是线程!!"+"线程名:"+Thread.currentThread().getName());
                times++;
                /*设置程序休眠1s IDEA快捷键:选中该句 Ctrl+Alt+t*/
                try {
         
         
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
         
         
                    throw new RuntimeException(e);
                }
    
                if(times==80){
         
         
                    break;
                }
            }
        }
    }
    
    • 流程图如下:

      image-20240428210135910

    • 当子线程Thread-0结束 整个进程结束

    • 为什么要用start方法 不直接调用run方法呢?

      • 由以下start方法的源码可知 其中调用了start0方法 而实现多线程效果的其实是start0方法 并不是run方法 所以直接调用run方法 会直到run方法全部运行完毕 才会接着运行下面的代码 故并不会看到多线程效果
      • start0是本地方法 由JVM调用 底层由C/C++实现
      • start方法调用start0方法后 该线程并不会立刻执行 而是将线程变成了可运行状态 具体什么时候执行 取决于CPU(你自己电脑的操作系统 不同操作系统不同) 由CPU统一调度
public synchronized void start() {
   
   
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
   
   
            start0();
            started = true;
        } finally {
   
   
            try {
   
   
                if (!started) {
   
   
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
   
   
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }
  1. 实现Runnable接口 重写run方法
    • 该方法存在的原因:并不是所有类都可以继承Thread类的 由于Java是单继承(一个类最多只能继承一个父类) 所以当某个类 已经继承一个父类后 便不可再继承Thread类 来创建进程了 在这种情况下 就要通过实现Runnable接口来创建线程
    • 样例代码:

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值