java如何建立多线程
创建多线程的几种方法
继承Thread类
通过继承Thread类并重写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");
}
}
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");
});
thread.start();
}
}
实现Callable接口
需要返回结果或抛出异常时使用Callable,配合FutureTask和ExecutorService。示例代码:
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)
推荐的生产环境方案,通过线程池管理线程生命周期。示例代码:
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("Task executed by " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
关键注意事项
- 线程启动必须调用
start()而非直接调用run() - 推荐优先使用
Runnable或Callable,避免Java单继承限制 - 线程池可有效管理资源,避免频繁创建/销毁线程的开销
- 多线程共享数据时需使用
synchronized或Lock保证线程安全






