推荐答案
在 Java 中,创建线程的方式主要有以下几种:
继承
Thread类
通过继承Thread类并重写run()方法来创建线程。实现
Runnable接口
通过实现Runnable接口并实现run()方法,然后将Runnable实例传递给Thread类的构造函数来创建线程。实现
Callable接口
通过实现Callable接口并实现call()方法,然后使用ExecutorService来提交任务并获取Future对象。使用线程池
通过ExecutorService和Executors工具类来创建线程池,从而管理和复用线程。
本题详细解读
1. 继承 Thread 类
// www.javascriptcn.com code example
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running by extending Thread class");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}优点:简单直接,适合简单的线程任务。
缺点:由于 Java 不支持多继承,继承 Thread 类后无法再继承其他类。
2. 实现 Runnable 接口
// www.javascriptcn.com code example
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running by implementing Runnable interface");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}优点:避免了单继承的限制,适合需要继承其他类的场景。
缺点:无法直接返回线程执行结果。
3. 实现 Callable 接口
// www.javascriptcn.com code example
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Thread is running by implementing Callable interface";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
System.out.println(future.get());
executor.shutdown();
}
}优点:可以返回线程执行结果,适合需要获取线程执行结果的场景。
缺点:使用稍微复杂,需要配合 ExecutorService 使用。
4. 使用线程池
// www.javascriptcn.com code example
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable task = new MyRunnable();
executor.execute(task);
}
executor.shutdown();
}
}优点:线程池可以管理和复用线程,减少线程创建和销毁的开销,适合高并发场景。
缺点:需要合理配置线程池参数,避免资源浪费或线程饥饿。