Java 中有多种创建线程的方式,常见的有以下三种:
- 继承 Thread 类并重写 run() 方法
可以通过继承 Thread 类并重写 run() 方法来创建一个线程,例如:
public class MyThread extends Thread {
public void run() {
System.out.println("Hello, world!");
}
}
// 创建线程并启动
MyThread thread = new MyThread();
thread.start();
- 实现 Runnable 接口
可以通过实现 Runnable 接口并重写 run() 方法来创建一个线程,例如:
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Hello, world!");
}
}
// 创建线程并启动
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
- 使用 Callable 和 Future 接口
可以通过实现 Callable 接口并重写 call() 方法来创建一个可返回结果的线程,例如:
public class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
return 1 + 1;
}
}
// 创建线程并启动
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(callable);
int result = future.get();
System.out.println(result);
executor.shutdown();
这三种方式都可以用来创建线程,但是它们有一些区别:
- 继承 Thread 类的方式只适用于简单的线程创建,不利于代码的复用和扩展,因为 Java 不支持多继承。
- 实现 Runnable 接口的方式更加灵活,可以用来实现多个接口,提高代码的复用性和可维护性。
- 使用 Callable 和 Future 接口的方式可以在线程执行完毕后返回结果,提高线程的灵活性和可扩展性。
综上所述,使用实现 Runnable 接口的方式更为常见和推荐,因为它具有更好的代码复用性和可维护性,而使用 Callable 和 Future 接口的方式则更适合需要返回结果的线程任务。