Java 中实现 Runnable 接口的内部类和匿名内部类
在 Java 中,内部类和匿名内部类是两种嵌套类。这里,嵌套类指的是一个类在另一个类内部的类。内部类是在没有 static 关键字的情况下定义的嵌套类,即内部类是非静态嵌套类。没有名称的嵌套内部类类型称为匿名类。
Runnable 接口是创建 Java 多线程中线程的一种方式。Java 提供了多线程的功能来同时执行多个操作。在多线程中,操作被分成多个较小的部分,称为线程。让我们探索如何使用实现 Runnable 接口的内部类和匿名内部类。
实现 Runnable 接口的内部类和匿名内部类
在本节中,我们将学习实现 Runnable 接口的内部类和匿名内部类。
显示实现 Runnable 接口的内部类的 Java 程序
让我们从介绍内部类开始。
内部类
非静态或内部类可以访问其外部类的所有静态和非静态方法和成员变量。它也可以访问私有成员,但是外部类不能访问内部类的私有成员。内部类是最常用的嵌套类类型。
语法
class Class_otr {
// Outer class body
class Class_inn {
// Inner class body
}
}
为了创建类,我们使用了 'class' 关键字。'Class_otr' 是外部类的名称,'Class_inn' 是内部类的名称。
示例 1
以下示例演示了实现 Runnable 接口的内部类的实际实现。
方法
首先,定义一个外部类,并在其中定义实现 Runnable 接口的内部类。
在这个内部类中,创建它的构造函数并覆盖 'run()' 方法。
接下来,定义另一个方法,在这个方法中,创建内部类的两个实例。使用这些实例,创建两个线程来执行操作。然后,使用内置方法 'start()' 来启动线程的过程。
在 main() 方法中,创建一个外部类的实例并调用 'executeThread()' 方法来启动操作。
class OtrClass {
// Creating an Inner class that implements Runnable
class InrClass implements Runnable {
private String greet;
// Constructor
public InrClass(String greet) {
this.greet = greet;
}
// Overriding the run() method
public void run() {
System.out.println(greet);
}
}
// defining method to execute threads using inner classes
public void executeThread() {
// instances of the inner class
InrClass ic1 = new InrClass("Hello and Welcome!!");
InrClass ic2 = new InrClass("Tutorials Point");
// Creating threads with instances of inner class
Thread thr1 = new Thread(ic1);
Thread thr2 = new Thread(ic2);
// Start the threads
thr1.start();
thr2.start();
}
}
public class RunableExp1 {
public static void main(String[] args) {
OtrClass oc = new OtrClass(); // instance of Outer class
oc. executeThread(); // calling method to start threads
}
}
输出
Hello and Welcome!! Tutorials Point
显示实现 Runnable 接口的匿名内部类的 Java 程序
在进入程序之前,让我们讨论一下匿名内部类。
匿名内部类
如前所述,它是一种没有名称的内部类。它的声明和初始化同时发生。它主要用于覆盖方法。
我们可以使用 abstract 关键字来声明匿名类。
语法
Class_name object_name = new Class_name() {
return_type method_name() {
// code to be executed
}
};
示例 2
以下示例说明了实现 Runnable 接口的匿名内部类的用法。
方法
创建一个实现 Runnable 接口的抽象类。
然后,在 main() 方法内部创建一个匿名内部类,覆盖之前的抽象类。
在这个匿名内部类中,覆盖内置方法 'run()'。
创建一个线程并使用 'start()' 方法启动它。
// abstract class that implements Runnable
abstract class Anonymous implements Runnable { }
public class RunableExp2 {
public static void main(String args[]) {
// creating anonymous inner class
Anonymous thr = new Anonymous() {
// overriding run() method
public void run() {
System.out.println("Hello! from anonymous inner class");
}
};
Thread thr1 = new Thread(thr); // defining a thread
thr1.start(); // starting the thread
}
}
输出
Hello! from anonymous inner class
结论
我们从定义内部类和匿名内部类开始这篇文章,在下一节中,我们详细讨论了它们。此外,我们还发现了用于在 Java 中执行多线程操作的 Runnable 接口。我们已经看到了实现 Runnable 接口的内部类和匿名内部类的两个不同示例。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP