The First way is to extend the Thread class, and override the run() The extending class must override run() method which is the entry point of new thread.
Anonymous Inner class is an inner class that is declared without any class name and that’s why it’s called anonymous. You can define an anonymous inner class within a method or even within an argument to a method.
Anonymous class can be used to - Extend an class and override its method. Implement an interface and provide an implementation of its method.
Threads Using Anonymous Classes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassCreatingThreadsExample{ publicstaticvoidmain(String[] args){ System.out.println("Main Method Start"); new Thread(new Runnable() { publicvoidrun(){ for (int i = 0; i < 100; i++) { System.out.println("ThreadRunner : " + i); } } }).start(); } }
Threads Using Java 8 Lambda
Runnable is a functional interface and we can use lambda expressions to provide it’s implementation rather than using anonymous class.
Threads Using Anonymous Classes
1 2 3 4 5 6 7 8 9 10
publicclassCreatingThreadsExample{ publicstaticvoidmain(String[] args){ Runnable task = () -> { for (int i = 0; i < 100; i++) { System.out.println("ThreadRunner2 : " + i); } }; new Thread(task).start(); } }