阅读量:111
在Java中,线程可以通过以下三种主要方式创建:
- 继承Thread类: 创建一个类,继承自Thread类,并重写其run()方法。然后创建该类的实例,并调用start()方法来启动线程。
class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
- 实现Runnable接口: 创建一个类,实现Runnable接口,并重写其run()方法。然后创建该类的实例,并将其传递给Thread类的构造函数。最后调用Thread实例的start()方法来启动线程。
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
- 使用Java 8的lambda表达式(仅适用于函数式接口): 如果你的类已经实现了Runnable接口,或者你想要将一个现有的方法线程来执行,你可以使用lambda表达式来简化代码。
class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// 线程执行的代码
});
thread.start();
}
}
注意:实现Runnable接口的方法通常更受推荐,因为它允许你的类继承其他类(Java不支持多重继承)。而继承Thread类的方法限制了你的类只能有一个父类。