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

java创建线程

作者:刺眼的男ren   发布日期:2025-08-09   浏览:18

// 创建线程的方式一:继承Thread类
class MyThread extends Thread {
    public void run() {
        // 线程体
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "运行  " + i);
        }
    }
}

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

        // 创建线程的方式二:实现Runnable接口
        Runnable task = new Runnable() {
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println(Thread.currentThread().getName() + "运行  " + i);
                }
            }
        };

        Thread thread = new Thread(task, "MyRunnableThread");
        thread.start(); // 启动线程

        // 创建线程的方式三:使用lambda表达式(Java 8及以上)
        Thread lambdaThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "运行  " + i);
            }
        });
        lambdaThread.start(); // 启动线程
    }
}

解释说明:

  1. 继承Thread类

    • 创建一个继承自Thread类的子类,并重写run()方法。
    • 使用start()方法启动线程,这会调用run()方法中的代码。
  2. 实现Runnable接口

    • 实现Runnable接口并重写run()方法。
    • Runnable对象传递给Thread构造函数,然后调用start()方法启动线程。
  3. 使用Lambda表达式(Java 8及以上):

    • 使用Lambda表达式简化创建线程的代码,直接将线程体作为参数传递给Thread构造函数。

上一篇:java string转jsonarray

下一篇:java local

大家都在看

java连接数据库的代码

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java实体类转json字符串

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

Laravel 中文站