
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
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 Articles
- How to create a thread in Java
- How to create a thread using method reference in Java?\n
- How to create a thread using lambda expressions in Java?\n
- How to implement an interface using an anonymous inner class in Java?
- How to make a class thread-safe in Java?
- How to create a thread in JShell in Java 9?
- Java Program to Check if a given Class is an Anonymous Class
- How to use isAlive() method of Thread class in Java?
- How to implement lambda expression without creating an anonymous class in Java?
- Can an anonymous class have constructors in Java?
- Create a queue using LinkedList class in Java
- How to create a thread in C#?
- How to create a thread in android?
- How to create a thread without implementing the Runnable interface in Java?
- How to create etched border for a component using BorderFactory class in Java?

Advertisements