Advertisement
//An anonymous thread by extending the Thread class
class A
{
public static void main(String... ar)
{
Thread t= new Thread(){ //Creating an object of Anonymous class which extends Thread class and passing this object to the reference of Thread class.
public void run() //Anonymous class overriding run() method of Thread class
{
setName("Anonymous Thread");
System.out.println("Name of the other thread - " + getName());
for(int i=0;i<3;i++)
{
System.out.println(getName() + " " + i);
}
}
}; //Anonymous class ends here
//Starting anonymous thread
t.start();
//Gets the name of main thead
System.out.println("Name of main thread - "+ Thread.currentThread().getName());
}
}
Name of main thread - main
Name of the other thread - Anonymous Thread
Anonymous Thread 0
Anonymous Thread 1
Anonymous Thread 2
Advertisement
//An anonymous thread by implementing the Runnable interface
class A
{
public static void main(String... ar)
{
Runnable r = new Runnable(){ //Creating an object of Anonymous class that implemented Runnable interface
public void run() //Anonymous class implementing run() method of Runnable class
{
Thread t= Thread.currentThread();
t.setName("Anonymous Thread");
System.out.println("Name of the other thread - " + t.getName());
for(int i=0;i<3;i++)
{
System.out.println(t.getName() + " " + i);
}
}
};
Thread t= new Thread(r); //Passing the object of anonymous class to the constructor of Thread
t.start(); //Starting the anonymous thread
//Gets the name of main thead
System.out.println("Name of main thread - "+ Thread.currentThread().getName());
}
}
Name of main thread - main
Anonymous Thread 0
Anonymous Thread 1
Anonymous Thread 2
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement