Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java 创建线程

作者:ι错过了   发布日期:2025-02-20   浏览:114

// Java 创建线程的两种常见方式:继承 Thread 类和实现 Runnable 接口

// 方式一:继承 Thread 类
class MyThread extends Thread {
    @Override
    public void run() {
        // 线程执行的代码
        System.out.println("线程 " + Thread.currentThread().getName() + " 正在运行");
    }
}

public class CreateThreadExample1 {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();  // 启动线程
    }
}

// 方式二:实现 Runnable 接口
class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程执行的代码
        System.out.println("线程 " + Thread.currentThread().getName() + " 正在运行");
    }
}

public class CreateThreadExample2 {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();  // 启动线程
    }
}

解释说明:

  1. 继承 Thread 类

    • MyThread 类继承了 Thread 类,并重写了 run() 方法。run() 方法中包含了线程要执行的代码。
    • main 方法中,创建 MyThread 的实例并调用 start() 方法启动线程。
  2. 实现 Runnable 接口

    • MyRunnable 类实现了 Runnable 接口,并实现了 run() 方法。
    • main 方法中,创建 MyRunnable 的实例,并将其传递给 Thread 构造函数,然后调用 start() 方法启动线程。

这两种方式都可以用来创建和启动线程,但通常推荐使用实现 Runnable 接口的方式,因为它避免了单继承的限制,更符合面向对象的设计原则。

上一篇:java调用python接口

下一篇:java blockingqueue

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站