java多线程如何实现方法
继承Thread类
创建一个类继承Thread并重写run()方法,通过调用start()启动线程。
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表达式
通过Lambda简化Runnable的实现,直接定义run()逻辑。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread running via Lambda");
});
thread.start();
}
}
实现Callable接口
结合FutureTask获取线程返回值,适用于需要返回结果的场景。
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
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 {
FutureTask<String> task = new FutureTask<>(new MyCallable());
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get()); // 获取返回值
}
}
使用线程池(ExecutorService)
通过线程池管理线程生命周期,提高资源利用率。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
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()方法,否则不会启动新线程。 - 优先选择
Runnable或Callable,避免单继承限制。 - 线程同步需使用
synchronized或Lock解决并发问题。 - 线程池需显式关闭以防止资源泄漏。






