JAVA线程的建立方法

JAVA线程的建立方法

在JAVA中,线程的建立主要有两种方式:继承Thread类和实现Runnable接口。每种方法各有优缺点,适用于不同场景。

继承Thread类

通过继承Thread类并重写run()方法可以创建线程。以下是示例代码:

复制代码
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

继承Thread类的方式简单直接,但由于JAVA不支持多继承,如果类已经继承了其他类,就无法再继承Thread类。

实现Runnable接口

通过实现Runnable接口并实现run()方法可以创建线程。以下是示例代码:

复制代码
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Thread is running");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}

实现Runnable接口的方式更加灵活,因为可以避免单继承的限制,同时更适合多线程共享资源的场景。

使用Lambda表达式简化

从JAVA 8开始,可以使用Lambda表达式进一步简化Runnable接口的实现:

复制代码
public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread is running");
        });
        thread.start();
    }
}

这种方式代码更简洁,适用于简单的线程任务。

使用Callable和Future

如果需要线程有返回值,可以使用Callable接口和Future

复制代码
import java.util.concurrent.*;

class MyCallable implements Callable<String> {
    public String call() throws Exception {
        return "Thread result";
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new MyCallable());
        System.out.println(future.get());
        executor.shutdown();
    }
}

Callable接口允许线程返回结果,并通过Future获取结果,适用于需要返回值的场景。

使用线程池

为了提高线程管理效率,可以使用线程池:

复制代码
import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                System.out.println("Thread is running");
            });
        }
        executor.shutdown();
    }
}

线程池可以复用线程,减少线程创建和销毁的开销,适用于高并发场景。

相关推荐
zone77392 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant2 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
码路飞3 小时前
GPT-5.3 Instant 终于学会好好说话了,顺手对比了下同天发布的 Gemini 3.1 Flash-Lite
java·javascript
允许部分打工人先富起来3 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_3 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
SimonKing4 小时前
OpenCode AI编程助手如何添加Skills,优化项目!
java·后端·程序员
haosend4 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽4 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
Seven975 小时前
剑指offer-80、⼆叉树中和为某⼀值的路径(二)
java
怒放吧德德17 小时前
Netty 4.2 入门指南:从概念到第一个程序
java·后端·netty