线程的创建方式

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();
    }
}
相关推荐
萤丰信息41 分钟前
智慧园区能源革命:从“耗电黑洞”到零碳样本的蜕变
java·大数据·人工智能·科技·安全·能源·智慧园区
曹牧1 小时前
Eclipse为方法添加注释
java·ide·eclipse
是小胡嘛1 小时前
C++之Any类的模拟实现
linux·开发语言·c++
我叫张小白。2 小时前
Spring Boot拦截器详解:实现统一的JWT认证
java·spring boot·web·jwt·拦截器·interceptor
csbysj20202 小时前
Vue.js 混入:深入理解与最佳实践
开发语言
Gerardisite4 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want5954 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
coderxiaohan4 小时前
【C++】多态
开发语言·c++
gfdhy4 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
闲人编程5 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器