线程的创建方式

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();
    }
}
相关推荐
「QT(C++)开发工程师」3 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天4 小时前
0 初识C++
开发语言·c++
FfHUCisI4 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI4 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
秋饼4 小时前
JDK 27 企业级 AI 服务落地实战:G1 默认、紧凑对象头、后量子 TLS 与 JFR 脱敏全解析
java·ai·技术分享·后端开发
卓怡学长5 小时前
w176基于SpringBoot的医院管理系统
java·spring boot·spring·maven·intellij-idea
lemon_sjdk5 小时前
ObjectProperty
java·开发语言·算法
大模型码小白5 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
hh9505 小时前
Agent Plan x DeepSeek Harness:Agent 供应链安全与第三方插件审计
java·开发语言·安全·agent plan·adg成都社区·adg社区