Home >Java >javaTutorial >How to create thread using anonymous class in Java?
Threading is a function that can be executed simultaneously with other parts of the program. All Java programs have at least one thread, called the main thread, which is run by the Java Virtual Machine (JVM) when the program starts and when the main() method is executed. Created and called together with the main thread.
In Java, we can create threads by Extending threads Classor implement Runnable interface through . We can also create threads using anonymousclasswithout extending Thread classin the following program.
public class AnonymousThreadTest { public static void main(String[] args) { new Thread() { public void run() { for (int i=1; i <= 5; i++) { System.out.println("run() method: " + i); } } }.start(); for (int j=1; j <= 5; j++) { System.out.println("main() method: " + j); } } }
main() method: 1 run() method: 1 main() method: 2 run() method: 2 main() method: 3 run() method: 3 main() method: 4 run() method: 4 main() method: 5 run() method: 5
The above is the detailed content of How to create thread using anonymous class in Java?. For more information, please follow other related articles on the PHP Chinese website!