如何在Java中创建和启动线程
为了在Java中创建线程,我们需要获取java.lang.Thread类的实例。我们可以通过两种方式进行。
- 通过实现Runnable接口。
- 通过扩展Thread类。
我们选择这两种方式中的任一种来在Java中创建线程,都需要重写run()方法并提供将在该线程中运行的代码。在创建的线程上调用start()方法后,将执行线程的run()方法。
在Java中创建和启动线程涉及以下步骤。
- 获取Thread类的实例。
- 在创建的线程对象上调用start方法。
- 线程启动后,将执行run方法。
通过实现Runnable接口创建线程
用Java创建线程的一种方法是实现Runnable接口。
可运行接口是Java中的功能接口,具有必须实现的单个方法run()。
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
使用Runnable的示例代码
public class TestThread implements Runnable {
@Override
public void run() {
System.out.println("Executing run method");
}
}
在此阶段,我们将拥有一个类型为Runnable的类(尚未为Thread类型)。 Thread类具有构造函数,我们可以在其中传递runnable作为参数,使用这些构造函数之一可以获取线程实例。
通常用于创建线程的那些构造函数中的两个如下:
- 线程(可运行目标)
- 线程(可运行目标,字符串名称)
我们需要将Runnable实例传递给这些构造函数之一来创建线程。以下代码显示了如何执行此操作。
public class ThreadDemo {
public static void main(String[] args) {
// Passing an instance of type runnable
Thread thread = new Thread(new TestThread());
thread.start();
}
}
运行此代码将实例化线程并启动它。最终,run()方法将由线程执行。
输出:
Executing run method
通过扩展Thread类创建线程
在Java中创建线程的另一种方法是继承Thread类的子类并覆盖run方法。然后,我们可以创建该类的实例并调用start()方法。
public class TestThread extends Thread {
@Override
public void run() {
System.out.println("Executing run method");
}
public static void main(String[] args) {
TestThread thread = new TestThread();
thread.start();
}
}
输出:
Executing run method
选择哪种方法
由于有两种方法可以在Java中创建线程,因此出现了一个问题,即应使用这两种方法中的哪一种。首选方法是实现Runnable接口。
当我们实现Runnable接口时,我们仍可以选择扩展另一个类,因为我们没有扩展Thread类。请注意,在Java中,我们只能扩展一个类。
线程类除了run()方法外还有许多其他方法,但是大多数情况下,我们将覆盖run()方法并提供必须由Thread执行的代码。通过实现Runnable接口可以完成相同的操作。如果我们不修改或者增强Thread类的任何其他方法,那么为什么要扩展它。
使用匿名类实现run()方法
通过扩展Thread类或者实现Runnable接口在Java中创建线程时,还可以使用匿名类来实现run方法。
扩展Thread类时
我们可以有一个匿名的内部类来扩展一个类而不实际扩展该类。我们可以创建一个匿名内部类并在其中提供运行方法实现。
public class TestThread {
public static void main(String[] args) {
// anonymous inner class
Thread thread = new Thread(){
@Override
public void run() {
System.out.println("Executing run method");
}
};
thread.start();
}
}
实施Runnable接口时
public class TestThread {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Executing run method");
}
}).start();
}
}
将Runnable实现为lambda表达式
由于Runnable是功能性接口,因此它也可以从Java 8开始实现为lambda表达式。
public class TestThread {
public static void main(String[] args) {
Runnable r = () -> {System.out.println("Executing run method");};
// passing runnable instance
new Thread(r).start();
}
}

