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 接口并重写 run() 方法,可以避免单继承的限制:
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 表达式
利用 Lambda 表达式简化 Runnable 接口的实现:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
thread.start();
}
}
使用 ExecutorService
通过 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
Callable 接口可以返回执行结果,适用于需要获取线程执行结果的场景:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
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();
}
}
注意事项
- 线程启动必须调用
start()方法,而不是直接调用run()方法。 - 避免直接继承
Thread类,推荐使用Runnable或Callable接口。 - 使用线程池(如
ExecutorService)可以更好地管理资源,避免频繁创建和销毁线程的开销。







