第二部分:Java 中的线程创建
一、Java 中的线程创建
在 Java 中,我们可以通过以下三种方式来创建线程:继承 Thread
类、实现 Runnable
接口、使用 Callable
和 Future
。每种方式各有特点,适合不同的应用场景。
二、使用 Thread
类创建线程
Thread
是 Java 提供的基础线程类,直接继承它并重写 run()
方法即可创建线程。
步骤:
- 定义一个类继承
Thread
。 - 重写
run()
方法,将线程执行的任务放入run()
中。 - 创建该类的实例,并调用
start()
方法启动线程。
示例代码:
class MyThread extends Thread {
@Override
public void run() {
// 线程的任务代码
System.out.println("你好,来自 MyThread!当前线程:" + Thread.currentThread().getName());
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程,自动调用 run() 方法
}
}
说明:
start()
方法会启动新线程并调用run()
方法。如果直接调用run()
而不使用start()
,任务将在当前线程中运行,而不会启动新线程。
三、使用 Runnable
接口创建线程
相比继承 Thread
,实现 Runnable
接口更灵活,因为 Java 是单继承,直接继承 Thread
限制了类的扩展性。Runnable
更适合需要继承其他类的情况下使用。
步骤:
- 创建一个类实现
Runnable
接口。 - 重写
run()
方法。 - 使用
Thread
构造函数创建一个新线程,并传入Runnable
实例。 - 调用
start()
方法启动线程。
示例代码:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("你好,来自 MyRunnable!当前线程:" + Thread.currentThread().getName());
}
}
public class RunnableExample {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable); // 传入 Runnable 实例
thread.start(); // 启动线程
}
}
四、使用 Callable
和 Future
创建线程
Runnable
接口的 run()
方法没有返回值,无法抛出异常。如果需要在线程执行后获取结果或处理异常,可以使用 Callable
和 Future
。
步骤:
- 实现
Callable
接口,并重写call()
方法。call()
可以返回结果并抛出异常。 - 使用
ExecutorService
提交Callable
任务,得到一个Future
对象。 - 通过
Future.get()
方法获取任务结果。
示例代码:
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() {
return "你好,来自 MyCallable!";
}
}
public class CallableExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
try {
String result = future.get(); // 获取任务结果
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
五、选择合适的方式
- 继承
Thread
:适合简单任务,但因为单继承限制,不够灵活。 - 实现
Runnable
:更灵活,适合多数场景,尤其是需要复用线程代码的情况。 - 使用
Callable
和Future
:适合需要线程返回结果或抛出异常的场景。
总结
Java 提供了三种不同的线程创建方式,每种方式适用于不同的开发需求。下一步,我们将学习 线程的生命周期和状态,深入了解线程在不同阶段的状态变化和常用的控制方法。掌握了这些方法,让你从容应对多线程编程的复杂性。