How to create a thread by using anonymous class in Java?


A Thread is a functionality which can be executed simultaneously with the other part of the program. All Java programs have at least one thread, known as the main thread, which is created by the Java Virtual Machine (JVM) at the program start when the main() method is invoked with the main thread.

In Java, we can create a thread by extending a Thread class or by implementing the Runnable interface. We can also create a thread by using the anonymous class without extending a Thread class in the below program.

Example

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);
      }
   }
}

Output

main() method: 1
main() method: 2
run() method: 1
main() method: 3
run() method: 2
main() method: 4
run() method: 3
main() method: 5
run() method: 4
run() method: 5

Updated on: 23-Nov-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements