线程的创建方式

1、继承Thread,重写run方法

通过自定义一个类(比如MyThread),使其继承Thread类,然后对run方法进行重写,最后在main方法中new出MyThread实例,然后调用所继承的start方法创建一个线程(注意,仅仅创建MyThread并不是在系统中创建一个线程,只有调用start时,才创建出一个线程)

java 复制代码
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("继承Thread,重写run方法创建线程");
    }
}
 
public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
    }
}

2、实现Runnable接口,重写run方法

通过自定义一个类(这里起名为:MyRunnable)实现Runnable接口,重写run方法,最后在main方法new出MyRunnable实例和Thread实例,最后通过start方法创建并启动线程。

java 复制代码
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("实现Runnable接口,重写run方法");
    }
}
 
public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

3、使用匿名内部类创建Thread子类对象

直接创建Thread子类,同时实例化出一个对象,重写run方法,最后通过start方法创建并启动线程。

java 复制代码
public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                System.out.println("使用匿名内部类创建 Thread 子类对象");
            }
        };
        thread.start();
    }
}
相关推荐
寻星探路5 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly2024067 小时前
Bootstrap 警告框
开发语言
2601_949146537 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧7 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX8 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01038 小时前
C++课后习题训练记录Day98
开发语言·c++
爬山算法8 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7258 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎8 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄8 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea