温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java Runnable可运行怎么用

发布时间:2026-10-25 13:55:16 来源:亿速云 阅读:96 作者:小樊 栏目:编程语言

在 Java 中,Runnable 是一个函数式接口(@FunctionalInterface),用来表示“可以被线程执行的任务”。
它本身不会启动线程,只是定义“要做什么”。


一、Runnable 是什么

@FunctionalInterface
public interface Runnable {
    void run();
}
  • 只有一个方法:run()
  • 没有返回值
  • 不能抛出受检异常

二、最基础的用法(实现 Runnable)

方式 1:实现 Runnable 接口

class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("任务执行中:" + Thread.currentThread().getName());
    }
}

使用:

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

方式 2:匿名内部类(老写法)

Runnable task = new Runnable() {
    @Override
    public void run() {
        System.out.println("匿名类任务");
    }
};

new Thread(task).start();

方式 3:Lambda 表达式(最常用 ✅)

Runnable task = () -> {
    System.out.println("Lambda 任务");
};

new Thread(task).start();

或直接:

new Thread(() -> {
    System.out.println("直接启动线程");
}).start();

三、Runnable 和 Thread 的区别

对比 Runnable Thread
是否任务 ✅ 是 ❌ 既是任务又是线程
是否启动线程 ❌ 否 ✅ 是
推荐程度 ✅ 推荐 ❌ 不推荐直接继承

✅ 推荐:任务用 Runnable,线程由 Thread 或线程池管理


四、配合线程池使用(真实开发最常见 ✅)

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);

        Runnable task = () -> {
            System.out.println("线程池任务");
        };

        pool.execute(task);
        pool.shutdown();
    }
}

五、Runnable 不能返回结果怎么办?

如果需要返回值,用:

  • Callable
  • Future

示例:

Callable<Integer> callable = () -> 1 + 1;

六、常见错误 ❌

错误 1:直接调用 run()

task.run(); // ❌ 只是普通方法,不会开线程

✅ 正确:

new Thread(task).start();

错误 2:Runnable 里抛异常

Runnable r = () -> {
    throw new IOException(); // ❌ 编译错误
};

七、一句话总结

Runnable = 定义“要做什么”
Thread / 线程池 = 决定“什么时候做、谁来做”

如果你愿意,我也可以帮你写:

  • 多线程示例
  • Runnable + 线程池完整案例
  • Runnable vs Callable 对比图
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手