
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 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
- Related Questions & Answers
- How to create a thread in Java
- How to create a thread using lambda expressions in Java?
- How to create a thread using method reference in Java?
- How to make a class thread-safe in Java?
- How to implement an interface using an anonymous inner class in Java?
- How to create a thread in JShell in Java 9?
- How to create a thread in C#?
- How to create a thread in android?
- Can an anonymous class have constructors in Java?
- How to use isAlive() method of Thread class in Java?
- Create a queue using LinkedList class in Java
- How to implement lambda expression without creating an anonymous class in Java?
- How to implement interface in anonymous class in C#?
- What is the Thread class in Java?
- Differences between anonymous class and lambda expression in Java?
Advertisements