Java 多线程有 4 种创建线程的方式,你都知道吗? 先直接总结,然后我会分类介绍:
- 继承 Thread 类
- 实现 Runnable 接口
- 通过匿名类
- 通过 Lambda 表达式
继承 Thread 类
首先我们可以通过继承 Thread 类,重载 Run 方法类创建线程。代码示例如下:
public class ThreadingWithSubClass extends Thread {
@Override
public void run() {
System.out.println(MessageFormat.format("Threading With SubClass. Thread ID: {0}", Thread.currentThread()));
}
}
创建线程的时候,我们需要创建一个类的实例。
// Threading with subclass
ThreadingWithSubClass thread2 = new ThreadingWithSubClass();
thread2.start();
实现 Runnable 接口
第二种方法是通过实现 Runnable 接口,重载 Run 方法。
public class ThreadingWithInterface implements Runnable {
@Override
public void run() {
System.out.println(MessageFormat.format("Threading With Interface. Thread ID: {0}", Thread.currentThread()));
}
}
创建线程的时候,我们需要把这个接口作为参数床给Thread类。
// Threading with interface
ThreadingWithInterface myThread1 = new ThreadingWithInterface();
Thread thread1 = new Thread(myThread1);
thread1.start();
通过匿名类
上面的两个方法我们都需要创建额外的类。使用匿名类方法我们可以直接在代码中加入线程处理的代码,然后启动线程:
// Threading with anonymous class
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(MessageFormat.format("Threading with anonymous class. Thread ID: {0}", Thread.currentThread()));
}
});
thread3.start();
通过 Lambda 表达式
如果觉得匿名类方式创建线程还是啰嗦,我们可以使用 Lambda 表达式来直接创建线程,因为 Runnable 接口被声明为了功能性接口 (Functional Interface),我们可以使用 Lambda 表达式来直接实现它。
// Threading with lambda
Thread thread4 = new Thread(()->{
System.out.println(MessageFormat.format("Threading with lambda. Thread ID: {0}", Thread.currentThread()));
});
thread4.start();
总结
我们介绍了创建 Java 线程的 4 种方式。它们分别是类继承,接口实现,匿名类以及 Lambda 表达式。其中 Lambda 表达式最后简洁。其他的 3 种方式为我们提供了更多的灵活性。