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();
    }
}

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

相关推荐
骇客野人6 分钟前
Java BIO / NIO / AIO 完整详解 + 编程技巧
java·开发语言·nio
霸道流氓气质9 分钟前
OpenTelemetry 入门与实战:Java Agent、Spring Boot Starter与LLM调用追踪示例
java·开发语言·spring boot
波力海苔夹心脆67514 分钟前
C# 机器视觉实战:单相机引导机械手精准贴合,从拍照、偏差计算(平移+旋转)到坐标补偿全解
开发语言·经验分享·数码相机·c#·视觉检测·.net
m0_5873830014 分钟前
24 小时自助健身房系统软件开发实战指南与案例解析
java·spring boot·spring·系统架构·需求分析
勿信日志15 分钟前
Playwright 元素定位:一个 width>50 过滤器把 42px 的输入框删掉了
python
larance20 分钟前
[菜鸟教程] 机器学习教程十课-Python 机器学习应用
人工智能·python·机器学习
栖凤20 分钟前
Java 的 try-catch 在 Agent 里失效了,我用了 5 个模式才兜住
java·前端·python
小师兄吃牛肉21 分钟前
Java 同步系列之 ZooKeeper 分布式锁
java·分布式·java-zookeeper
Yyyyyy~28 分钟前
【python】函数
python
金銀銅鐵29 分钟前
[Java] 借助GUI展示class文件的版本号
后端·python·ai编程