Java 线程创建中 Thread 和 Runnable 有什么区别
thread 是类,runnable 是接口。使用 thread 需要继承,导致无法再继承其他类;使用 runnable 只需实现接口,支持组合模式,且能共享同一个 runnable 实例给多个 thread 对象。

为什么推荐使用 Runnable 而不是直接继承 Thread
因为 Java 不支持多继承。如果业务逻辑已经继承了某个父类,就无法再继承 Thread。通过实现 Runnable 接口,可以将“任务”与“执行者”分离,提高代码的复用性和灵活性。

使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
public class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Running task in thread: " + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread t1 = new Thread(task, "Thread-1");
Thread t2 = new Thread(task, "Thread-2");
t1.start();
t2.start();
}
}
在什么情况下 Thread 和 Runnable 的行为会有差异
当多个线程共享同一个 Runnable 实例时,它们操作的是同一份数据。而如果每个线程都创建独立的 Thread 子类实例,则通常各自拥有独立的状态(除非显式共享)。此外,Thread 类本身包含了一些管理线程生命周期的方法(如 interrupt、isAlive),而 Runnable 仅定义任务逻辑。

public class SharedData {
private int count = 0;
public synchronized void increment() {
count++;
System.out.println(Thread.currentThread().getName() + " incremented to " + count);
}
}
public class IncrementTask implements Runnable {
private SharedData data;
public IncrementTask(SharedData data) { this.data = data; }
@Override
public void run() {
for (int i = 0; i
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










