java 如何开启线程
在 Java 中开启线程的方法
Java 提供了多种开启线程的方式,以下是常见的几种方法:
继承 Thread 类
通过继承 Thread 类并重写 run() 方法,可以创建并启动线程:

class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
实现 Runnable 接口
通过实现 Runnable 接口并传递给 Thread 类,可以更灵活地创建线程:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}
}
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 is running");
});
thread.start(); // 启动线程
}
}
使用 ExecutorService(推荐)
通过线程池管理线程,更高效且可控:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Thread is running");
});
executor.shutdown(); // 关闭线程池
}
}
使用 Callable 和 Future
适用于需要返回结果或抛出异常的线程任务:
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return "Thread result";
}
});
System.out.println(future.get()); // 获取线程返回值
executor.shutdown();
}
}
注意事项
- 直接调用
run()方法不会启动新线程,而是会在当前线程中执行。 - 避免频繁创建和销毁线程,推荐使用线程池(如
ExecutorService)。 - 多线程环境下需注意线程安全和资源共享问题。






