java如何创建线程
在Java中创建线程主要有两种方式:继承Thread类和实现Runnable接口。以下是具体实现方法:
继承Thread类
通过继承Thread类并重写run()方法,可以创建一个线程。启动线程时调用start()方法而非直接调用run()方法。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running by extending Thread class");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
实现Runnable接口
通过实现Runnable接口并实现run()方法,将实例传递给Thread类的构造函数来创建线程。这种方式更灵活,适合需要多继承的场景。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running by implementing Runnable interface");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // 启动线程
}
}
使用Lambda表达式(Java 8+)
对于简单的任务,可以使用Lambda表达式简化Runnable接口的实现。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread running via Lambda expression");
});
thread.start();
}
}
使用Callable和Future(带返回值)
如果需要线程返回结果,可以使用Callable接口和Future。Callable的call()方法可以返回结果或抛出异常。
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Result from Callable";
}
}
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();
}
}
使用线程池(ExecutorService)
对于需要管理多个线程的场景,推荐使用线程池(如ExecutorService),避免频繁创建和销毁线程的开销。

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> System.out.println("Task executed by thread pool"));
executor.shutdown(); // 关闭线程池
}
}
注意事项
- 直接调用
run()方法不会启动新线程,仅在当前线程中执行。 - 线程启动后无法保证立即执行,由操作系统调度决定。
- 避免直接继承
Thread类,推荐优先使用Runnable或Callable接口。






