线程的创建方式

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();
    }
}
相关推荐
cdut_suye几秒前
Linux工具使用指南:从apt管理、gcc编译到makefile构建与gdb调试
java·linux·运维·服务器·c++·人工智能·python
苹果醋312 分钟前
2020重新出发,MySql基础,MySql表数据操作
java·运维·spring boot·mysql·nginx
小蜗牛慢慢爬行14 分钟前
如何在 Spring Boot 微服务中设置和管理多个数据库
java·数据库·spring boot·后端·微服务·架构·hibernate
azhou的代码园17 分钟前
基于JAVA+SpringBoot+Vue的制造装备物联及生产管理ERP系统
java·spring boot·制造
波音彬要多做25 分钟前
41 stack类与queue类
开发语言·数据结构·c++·学习·算法
Swift社区33 分钟前
Excel 列名称转换问题 Swift 解答
开发语言·excel·swift
一道微光37 分钟前
Mac的M2芯片运行lightgbm报错,其他python包可用,x86_x64架构运行
开发语言·python·macos
矛取矛求41 分钟前
QT的前景与互联网岗位发展
开发语言·qt
Leventure_轩先生41 分钟前
[WASAPI]从Qt MultipleMedia来看WASAPI
开发语言·qt
向宇it1 小时前
【从零开始入门unity游戏开发之——unity篇01】unity6基础入门开篇——游戏引擎是什么、主流的游戏引擎、为什么选择Unity
开发语言·unity·c#·游戏引擎