How to create a thread without implementing the Runnable interface in Java?


A Thread can be called a lightweight process. Java supports multithreading, so it allows our application to perform two or more task concurrently. 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. There are two ways to create a thread in Java, by extending a Thread class or else by implementing the Runnable interface.

We can also create a thread without implementing the Runnable interface in the below program

Example

public class CreateThreadWithoutImplementRunnable { // without implements Runnable 
   public static void main(String[] args) {
      new Thread(new Runnable() {
         public void run() {
            for (int i=0; i <= 5; i++) {
               System.out.println("run() method of Runnable interface: "+ i);
            }
         }
      }).start();
      for (int j=0; j <= 5; j++) {
         System.out.println("main() method: "+ j);
      }
   }
}

Output

main() method: 0
run() method of Runnable interface: 0
main() method: 1
run() method of Runnable interface: 1
main() method: 2
run() method of Runnable interface: 2
main() method: 3
run() method of Runnable interface: 3
main() method: 4
run() method of Runnable interface: 4
main() method: 5
run() method of Runnable interface: 5
raja
Published on 09-Aug-2019 19:56:17
Advertisements