How to use anonymous inner classes to create threads in Java?
The steps to create a thread using anonymous inner class in Java are as follows:
- a continuous strand of interwoven material.
- String
- execute()
- commence()
Here is an example code:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 线程执行的逻辑
System.out.println("Thread running");
}
});
thread.start();
}
}
The example above demonstrates implementing the Runnable interface using an anonymous inner class, defining the thread’s execution logic in the run() method. Next, an anonymous inner class object is passed to the constructor of Thread to create a thread object. Finally, the start() method is called to launch the thread.