hereral/Clara-Training-Data huggingface dataset:
Question: How to instantiate Member Inner class in Java?
Answer: An object or instance of a member's inner class always exists within an object of its outer class. The new operator is used to create the object of member inner class with slightly different syntax.

The general form of syntax to create an object of the member inner class is as follows:

Syntax:

OuterClassReference.new MemberInnerClassConstructor();  
Example:

obj.new Inner();
Question: What is the Internal working of Java member inner class?
Answer: The java compiler creates two class files in the case of the inner class. The class file name of the inner class is "Outer$Inner". If you want to instantiate the inner class, you must have to create the instance of the outer class. In such a case, an instance of inner class is created inside the instance of the outer class.
Question: What is the Internal code generated by the compiler in Java?
Answer: The Java compiler creates a class file named Outer$Inner in this case. The Member inner class has the reference of Outer class that is why it can access all the data members of Outer class including private.

import java.io.PrintStream;  
class Outer$Inner  
{  
    final Outer this$0;  
    Outer$Inner()  
    {   super();  
        this$0 = Outer.this;  
    }  
    void msg()  
    {  
        System.out.println((new StringBuilder()).append("data is ")  
                    .append(Outer.access$000(Outer.this)).toString());  
    }  
}
Question: What is Java Anonymous inner class?
Answer: Java anonymous inner class is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways:

1.Class (may be abstract or concrete).
2.Interface
Question: Can you provide a Java anonymous inner class example using class?
Answer: TestAnonymousInner.java

abstract class Person{  
  abstract void eat();  
}  
class TestAnonymousInner{  
 public static void main(String args[]){  
  Person p=new Person(){  
  void eat(){System.out.println("nice fruits");}  
  };  
  p.eat();  
 }  
}  
Output:

nice fruits
Question: Can you provide a Java anonymous inner class example using interface?
Answer: interface Eatable{  
 void eat();  
}  
class TestAnnonymousInner1{  
 public static void main(String args[]){  
 Eatable e=new Eatable(){  
  public void eat(){System.out.println("nice fruits");}  
 };  
 e.eat();  
 }  
}  
Output:

nice fruits
Question: What is Java Local inner class?
Answer: A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the inner classes that are defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop, or an if clause. Local Inner classes are not a member of any enclosing classes. They belong to the block they are defined within, due to which local inner classes cannot have any access modifiers associated with them. However, they can be marked as final or abstract. These classes have access to the fields of the class enclosing it.

If you want to invoke the methods of the local inner class, you must instantiate this class inside the method.
Question: Can you provide a Java local inner class example?
Answer: LocalInner1.java

public class localInner1{  
 private int data=30;//instance variable  
 void display(){  
  class Local{  
   void msg(){System.out.println(data);}  
  }  
  Local l=new Local();  
  l.msg();  
 }  
 public static void main(String args[]){  
  localInner1 obj=new localInner1();  
  obj.display();  
 }  
}  

Output:

30
Question: What is Internal class generated by the compiler?
Answer: In such a case, the compiler creates a class named Simple$1Local that has the reference of the outer class.

import java.io.PrintStream;  
class localInner1$Local  
{  
    final localInner1 this$0;  
    localInner1$Local()  
    {     
        super();  
        this$0 = Simple.this;  
    }  
    void msg()  
    {  
        System.out.println(localInner1.access$000(localInner1.this));  
    }  
}  
Rule: Local variables can't be private, public, or protected.
Question: What is the Rules for Java Local Inner class?
Answer: Rules for Java Local Inner class
1) Local inner class cannot be invoked from outside the method.
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in the local inner class.
Question: Can you give me an Example of local inner class with local variable?
Answer: LocalInner2.java

class localInner2{  
 private int data=30;//instance variable  
 void display(){  
  int value=50;//local variable must be final till jdk 1.7 only  
  class Local{  
   void msg(){System.out.println(value);}  
  }  
  Local l=new Local();  
  l.msg();  
 }  
 public static void main(String args[]){  
  localInner2 obj=new localInner2();  
  obj.display();  
 }  
}  

Output:

50
Question: What is Java static nested class?
Answer: A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name.

-It can access static data members of the outer class, including private.
-The static nested class cannot access non-static (instance) data members or
Question: Can you give me a Java static nested class example with instance method?
Answer: TestOuter1.java

class TestOuter1{  
  static int data=30;  
  static class Inner{  
   void msg(){System.out.println("data is "+data);}  
  }  
  public static void main(String args[]){  
  TestOuter1.Inner obj=new TestOuter1.Inner();  
  obj.msg();  
  }  
}  

Output:

data is 30
Question: Can you give me a Java static nested class example with a static method
Answer: If you have the static member inside the static nested class, you don't need to create an instance of the static nested class.

TestOuter2.java

public class TestOuter2{  
  static int data=30;  
  static class Inner{  
   static void msg(){System.out.println("data is "+data);}  
  }  
  public static void main(String args[]){  
  TestOuter2.Inner.msg();//no need to create the instance of static nested class  
  }  
}  

Output:

data is 30
Question: What is Java Nested Interface?
Answer: An interface, i.e., declared within another interface or class, is known as a nested interface. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface must be referred to by the outer interface or class. It can't be accessed directly.
Question: What are the Points to remember for nested interfaces?
Answer: There are given some points that should be remembered by the java programmer.

-The nested interface must be public if it is declared inside the interface, but it can have any access modifier if declared within the class.
-Nested interfaces are declared static
Question: What is the Syntax of nested interface which is declared within the interface?
Answer: interface interface_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}
Question: What is the Syntax of nested interface which is declared within the class?
Answer: class class_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}
Question: Can you give me an Example of nested interface which is declared within the interface?
Answer: In this example, we will learn how to declare the nested interface and how we can access it.

TestNestedInterface1.java

interface Showable{  
  void show();  
  interface Message{  
   void msg();  
  }  
}  
class TestNestedInterface1 implements Showable.Message{  
 public void msg(){System.out.println("Hello nested interface");}  
  
 public static void main(String args[]){  
  Showable.Message message=new TestNestedInterface1();//upcasting here  
  message.msg();  
 }  
}  

Output:

hello nested interface
Question: Can we define a class inside the interface?
Answer: Yes, if we define a class inside the interface, the Java compiler creates a static nested class. Let's see how can we define a class within the interface:

interface M{  
  class A{}  
}
Question: What is Multithreading in Java?
Answer: Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.
Question: What is the Advantages of Java Multithreading?
Answer: 1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Question: What is Thread in java?
Answer: A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a shared memory area.

Java Multithreading
As shown in the above figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads.
Question: What is Java Thread class?
Answer: Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
Question: What is the Life cycle of a Thread (Thread States)?
Answer: In Java, a thread always exists in any one of the following states. These states are:

1.New
2.Active
3.Blocked / Waiting
4.Timed Waiting
5.Terminated
Question: What are the Implementation of Thread States?
Answer: In Java, one can get the current state of a thread using the Thread.getState() method. The java.lang.Thread.State class of Java provides the constants ENUM to represent the state of a thread. These constants are:

public static final Thread.State NEW  
It represents the first state of a thread that is the NEW state.

public static final Thread.State RUNNABLE  
It represents the runnable state.It means a thread is waiting in the queue to run.

public static final Thread.State BLOCKED  
It represents the blocked state. In this state, the thread is waiting to acquire a lock.

public static final Thread.State WAITING  
It represents the waiting state. A thread will go to this state when it invokes the Object.wait() method, or Thread.join() method with no timeout. A thread in the waiting state is waiting for another thread to complete its task.

public static final Thread.State TIMED_WAITING  
It represents the timed waiting state. The main difference between waiting and timed waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has the time constraint. A thread invoking the following method reaches the timed waiting state.

-sleep
-join with timeout
-wait with timeout
-parkUntil
-parkNanos
public static final Thread.State TERMINATED  
It represents the final state of a thread that is terminated or dead. A terminated thread means it has completed its execution.
Question: Can you give me an example of Java Program for Demonstrating Thread States?
Answer: The following Java program shows some of the states of a thread defined above.

FileName: ThreadState.java

// ABC class implements the interface Runnable  
class ABC implements Runnable  
{  
public void run()  
{  
  
// try-catch block  
try  
{  
// moving thread t2 to the state timed waiting  
Thread.sleep(100);  
}  
catch (InterruptedException ie)  
{  
ie.printStackTrace();  
}  
  
  
System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -"+ ThreadState.t1.getState());  
  
// try-catch block  
try  
{  
Thread.sleep(200);  
}  
catch (InterruptedException ie)  
{  
ie.printStackTrace();  
}     
}  
}  
  
// ThreadState class implements the interface Runnable  
public class ThreadState implements Runnable  
{  
public static Thread t1;  
public static ThreadState obj;  
  
// main method   
public static void main(String argvs[])  
{  
// creating an object of the class ThreadState  
obj = new ThreadState();  
t1 = new Thread(obj);  
  
// thread t1 is spawned   
// The thread t1 is currently in the NEW state.  
System.out.println("The state of thread t1 after spawning it - " + t1.getState());  
  
// invoking the start() method on   
// the thread t1  
t1.start();  
  
// thread t1 is moved to the Runnable state  
System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState());  
}  
  
public void run()  
{  
ABC myObj = new ABC();  
Thread t2 = new Thread(myObj);  
  
// thread t2 is created and is currently in the NEW state.  
System.out.println("The state of thread t2 after spawning it - "+ t2.getState());  
t2.start();  
  
// thread t2 is moved to the runnable state  
System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState());  
  
// try-catch block for the smooth flow of the  program  
try  
{  
// moving the thread t1 to the state timed waiting   
Thread.sleep(200);  
}  
catch (InterruptedException ie)  
{  
ie.printStackTrace();  
}  
  
System.out.println("The state of thread t2 after invoking the method sleep() on it - "+ t2.getState() );  
  
// try-catch block for the smooth flow of the  program  
try  
{  
// waiting for thread t2 to complete its execution  
t2.join();  
}  
catch (InterruptedException ie)  
{  
ie.printStackTrace();  
}  
System.out.println("The state of thread t2 when it has completed it's execution - " + t2.getState());  
}  
  
}  
Output:

The state of thread t1 after spawning it - NEW
The state of thread t1 after invoking the method start() on it - RUNNABLE
The state of thread t2 after spawning it - NEW
the state of thread t2 after calling the method start() on it - RUNNABLE
The state of thread t1 while it invoked the method join() on thread t2 -TIMED_WAITING
The state of thread t2 after invoking the method sleep() on it - TIMED_WAITING
The state of thread t2 when it has completed it's execution - TERMINATED
Question: Java Threads | How to create a thread in Java?
Answer: There are two ways to create a thread:

1.By extending Thread class
2.By implementing Runnable interface.
Question: What are the Commonly used Constructors of Thread class?
Answer: Commonly used Constructors of Thread class:
-Thread()
-Thread(String name)
-Thread(Runnable r)
-Thread(Runnable r,String name)
Question: What are the Commonly used methods of Thread class?
Answer: 1.public void run(): is used to perform action for a thread.
2.public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
3.public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
4.public void join(): waits for a thread to die.
5.public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6.public int getPriority(): returns the priority of the thread.
7.public int setPriority(int priority): changes the priority of the thread.
8.public String getName(): returns the name of the thread.
9.public void setName(String name): changes the name of the thread.
10.public Thread currentThread(): returns the reference of currently executing thread.
11.public int getId(): returns the id of the thread.
12.public Thread.State getState(): returns the state of the thread.
13.public boolean isAlive(): tests if the thread is alive.
14.public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
15.public void suspend(): is used to suspend the thread(depricated).
16.public void resume(): is used to resume the suspended thread(depricated).
17.public void stop(): is used to stop the thread(depricated).
18.public boolean isDaemon(): tests if the thread is a daemon thread.
19.public void setDaemon(boolean b): marks the thread as daemon or user thread.
20.public void interrupt(): interrupts the thread.
21.public boolean isInterrupted(): tests if the thread has been interrupted.
22.public static boolean interrupted(): tests if the current thread has been interrupted.
Question: What is Runnable interface?
Answer: The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

1.public void run(): is used to perform action for a thread.
Question: How to Start a thread in Java?
Answer: The start() method of Thread class is used to start a newly created thread. It performs the following tasks:

-A new thread starts(with new callstack).
-The thread moves from New state to the Runnable state.
-When the thread gets a chance to execute, its target run() method will run.
Question: Can you give me a Java Thread Example by extending Thread class?
Answer: FileName: Multi.java

class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
Output:

thread is running...
Question: Can you give me a Java Thread Example by implementing Runnable interface?
Answer: FileName: Multi3.java

class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);   // Using the constructor Thread(Runnable r)  
t1.start();  
 }  
}  
Output:

thread is running...
Question: How to use the Thread Class: Thread(String Name)?
Answer: We can directly use the Thread class to spawn new threads using the constructors defined above.

FileName: MyThread1.java

public class MyThread1  
{  
// Main method  
public static void main(String argvs[])  
{  
// creating an object of the Thread class using the constructor Thread(String name)   
Thread t= new Thread("My first thread");  
  
// the start() method moves the thread to the active state  
t.start();  
// getting the thread name by invoking the getName() method  
String str = t.getName();  
System.out.println(str);  
}  
}  
Output:

My first thread
Question: How to use the Thread Class: Thread(Runnable r, String name)?
Answer: Observe the following program.

FileName: MyThread2.java

public class MyThread2 implements Runnable  
{    
public void run()  
{    
System.out.println("Now the thread is running ...");    
}    
    
// main method  
public static void main(String argvs[])  
{   
// creating an object of the class MyThread2  
Runnable r1 = new MyThread2();   
  
// creating an object of the class Thread using Thread(Runnable r, String name)  
Thread th1 = new Thread(r1, "My new thread");    
  
// the start() method moves the thread to the active state  
th1.start();   
  
// getting the thread name by invoking the getName() method  
String str = th1.getName();  
System.out.println(str);  
}    
}    
Output:

My new thread
Now the thread is running ...
Question: What is Thread Scheduler in Java?
Answer: A component of Java that decides which thread to run or execute and which thread to wait is called a thread scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it is in the runnable state. However, if there is more than one thread in the runnable state, it is up to the thread scheduler to pick one of the threads and ignore the other ones. There are some criteria that decide which thread will execute first. There are two factors for scheduling a thread i.e. Priority and Time of arrival.

Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it means that thread has got a better chance of getting picked up by the thread scheduler.

Time of Arrival: Suppose two threads of the same priority enter the runnable state, then priority cannot be the factor to pick a thread from these two threads. In such a case, arrival time of thread is considered by the thread scheduler. A thread that arrived first gets the preference over the other threads.
Question: What is the Working of the Java Thread Scheduler?
Answer: Let's understand the working of the Java thread scheduler. Suppose, there are five threads that have different arrival times and different priorities. Now, it is the responsibility of the thread scheduler to decide which thread will get the CPU first.

The thread scheduler selects the thread that has the highest priority, and the thread begins the execution of the job. If a thread is already in runnable state and another thread (that has higher priority) reaches in the runnable state, then the current thread is pre-empted from the processor, and the arrived thread with higher priority gets the CPU time.

When two threads (Thread 2 and Thread 3) having the same priorities and arrival time, the scheduling will be decided on the basis of FCFS algorithm. Thus, the thread that arrives first gets the opportunity to execute first.
Question: What is Thread.sleep() in Java?
Answer: The Java Thread class provides the two variant of the sleep() method. First one accepts only an arguments, whereas the other variant accepts two arguments. The method sleep() is being used to halt the working of a thread for a given amount of time. The time up to which the thread remains in the sleeping state is known as the sleeping time of the thread. After the sleeping time is over, the thread starts its execution from where it has left.
Question: What is The sleep() Method Syntax in Java?
Answer: Following are the syntax of the sleep() method.

public static void sleep(long mls) throws InterruptedException   
public static void sleep(long mls, int n) throws InterruptedException   
The method sleep() with the one parameter is the native method, and the implementation of the native method is accomplished in another programming language. The other methods having the two parameters are not the native method. That is, its implementation is accomplished in Java. We can access the sleep() methods with the help of the Thread class, as the signature of the sleep() methods contain the static keyword. The native, as well as the non-native method, throw a checked Exception. Therefore, either try-catch block or the throws keyword can work here.

The Thread.sleep() method can be used with any thread. It means any other thread or the main thread can invoke the sleep() method.
Question: What are the Important Points to Remember About the Sleep() Method?
Answer: Whenever the Thread.sleep() methods execute, it always halts the execution of the current thread.

Whenever another thread does interruption while the current thread is already in the sleep mode, then the InterruptedException is thrown.

If the system that is executing the threads is busy, then the actual sleeping time of the thread is generally more as compared to the time passed in arguments. However, if the system executing the sleep() method has less load, then the actual sleeping time of the thread is almost equal to the time passed in the argument.
Question: Can you give me an Example of the sleep() method in Java : on the custom thread?
Answer: e){System.out.println(e);}    
    System.out.println(i);    
  }    
 }    
 public static void main(String args[]){    
  TestSleepMethod1 t1=new TestSleepMethod1();    
  TestSleepMethod1 t2=new TestSleepMethod1();    
     
  t1.start();    
  t2.start();    
 }    
}    
Output:

1
1
2
2
3
3
4
4
Question: Can you give me an Example of the sleep() Method in Java : on the main thread?
Answer: FileName: TestSleepMethod2.java

// important import statements  
import java.lang.Thread;  
import java.io.*;  
  
  
public class TestSleepMethod2  
{  
    // main method  
public static void main(String argvs[])  
{  
  
try {  
for (int j = 0; j < 5; j++)  
{  
  
// The main thread sleeps for the 1000 milliseconds, which is 1 sec  
// whenever the loop runs  
Thread.sleep(1000);  
  
// displaying the value of the variable  
System.out.println(j);  
}  
}  
catch (Exception expn)   
{  
// catching the exception  
System.out.println(expn);  
}  
}  
}  
Output:

0
1
2
3
4
Question: Can you give me an Example of the sleep() Method in Java: When the sleeping time is -ive?
Answer: The following example throws the exception IllegalArguementException when the time for sleeping is negative.

FileName: TestSleepMethod3.java

// important import statements  
import java.lang.Thread;  
import java.io.*;  
  
public class TestSleepMethod3  
{  
// main method  
public static void main(String argvs[])  
{  
// we can also use throws keyword followed by  
// exception name for throwing the exception  
try   
{  
for (int j = 0; j < 5; j++)   
{  
  
// it throws the exception IllegalArgumentException  
// as the time is -ive which is -100  
Thread.sleep(-100);  
  
// displaying the variable's value  
System.out.println(j);  
}  
}  
catch (Exception expn)   
{  
  
// the exception iscaught here   
System.out.println(expn);  
}  
}  
}  
Output:

java.lang.IllegalArgumentException: timeout value is negative
Question: Can we start a thread twice?
Answer: No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

Let's understand it by the example given below:

public class TestThreadTwice1 extends Thread{  
 public void run(){  
   System.out.println("running...");  
 }  
 public static void main(String args[]){  
  TestThreadTwice1 t1=new TestThreadTwice1();  
  t1.start();  
  t1.start();  
 }  
}  

Output:

running
Exception in thread "main" java.lang.IllegalThreadStateException
Question: What if we call Java run() method directly instead start() method?
Answer: Each thread starts in a separate call stack.
Invoking the run() method from the main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
FileName: TestCallRun1.java

class TestCallRun1 extends Thread{  
 public void run(){  
   System.out.println("running...");  
 }  
 public static void main(String args[]){  
  TestCallRun1 t1=new TestCallRun1();  
  t1.run();//fine, but does not start a separate call stack  
 }  
}  

Output:

running...
Question: What is Java join() method?
Answer: The join() method in Java is provided by the java.lang.Thread class that permits one thread to wait until the other thread to finish its execution. Suppose th be the object the class Thread whose thread is doing its execution currently, then the th.join(); statement ensures that th is finished before the program does the execution of the next statement. When there are more than one thread invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to mention the waiting period. However, similar to the sleep() method in Java, the join() method is also dependent on the operating system for the timing, so we should not assume that the join() method waits equal to the time we mention in the parameters. The following are the three overloaded join() methods.
Question: Can you give me the Description of The Overloaded join() Method?
Answer: join(): When the join() method is invoked, the current thread stops its execution and the thread goes into the wait state. The current thread remains in the wait state until the thread on which the join() method is invoked has achieved its dead state. If interruption of the thread occurs, then it throws the InterruptedException.
Question: Can you give me an Example of join() Method in Java?
Answer: The following program shows the usage of the join() method.

FileName: ThreadJoinExample.java

// A Java program for understanding   
// the joining of threads  
  
// import statement  
import java.io.*;  
  
// The ThreadJoin class is the child class of the class Thread  
class ThreadJoin extends Thread  
{  
// overriding the run method  
public void run()  
{  
for (int j = 0; j < 2; j++)  
{  
try  
{  
// sleeping the thread for 300 milli seconds  
Thread.sleep(300);  
System.out.println("The current thread name is: " + Thread.currentThread().getName());  
}  
// catch block for catching the raised exception  
catch(Exception e)  
{  
System.out.println("The exception has been caught: " + e);  
}  
System.out.println( j );  
}  
}  
}  
  
public class ThreadJoinExample  
{  
// main method  
public static void main (String argvs[])  
{  
  
// creating 3 threads  
ThreadJoin th1 = new ThreadJoin();  
ThreadJoin th2 = new ThreadJoin();  
ThreadJoin th3 = new ThreadJoin();  
  
// thread th1 starts  
th1.start();  
  
// starting the second thread after when  
// the first thread th1 has ended or died.  
try  
{  
System.out.println("The current thread name is: "+ Thread.currentThread().getName());  
  
// invoking the join() method  
th1.join();  
}  
  
// catch block for catching the raised exception  
catch(Exception e)  
{  
System.out.println("The exception has been caught " + e);  
}  
  
// thread th2 starts  
th2.start();  
  
// starting the th3 thread after when the thread th2 has ended or died.  
try  
{  
System.out.println("The current thread name is: " + Thread.currentThread().getName());  
th2.join();  
}  
  
// catch block for catching the raised exception  
catch(Exception e)  
{  
System.out.println("The exception has been caught " + e);  
}  
  
// thread th3 starts  
th3.start();  
}  
}  
Output:

The current thread name is: main
The current thread name is: Thread - 0
0
The current thread name is: Thread - 0
1
The current thread name is: main
The current thread name is: Thread - 1
0
The current thread name is: Thread - 1
1
The current thread name is: Thread - 2
0
The current thread name is: Thread - 2
1
Question: What is The Join() Method: InterruptedException?
Answer: We have learnt in the description of the join() method that whenever the interruption of the thread occurs, it leads to the throwing of InterruptedException. The following example shows the same.

FileName: ThreadJoinExample1.java

class ABC extends Thread  
{  
Thread threadToInterrupt;  
// overriding the run() method  
public void run()  
{  
// invoking the method interrupt  
threadToInterrupt.interrupt();  
}  
}  
  
  
public class ThreadJoinExample1  
{  
// main method  
public static void main(String[] argvs)  
{  
try  
{  
// creating an object of the class ABC  
ABC th1 = new ABC();  
  
th1.threadToInterrupt = Thread.currentThread();  
th1.start();  
  
// invoking the join() method leads   
// to the generation of InterruptedException  
th1.join();  
}  
catch (InterruptedException ex)  
{  
System.out.println("The exception has been caught. " + ex);  
}  
}  
}  
Output:

The exception has been caught. java.lang.InterruptedException
Question: Can you give me Some More Examples of the join() Method?
Answer: Let' see some other examples.

Filename: TestJoinMethod1.java

class TestJoinMethod1 extends Thread{    
 public void run(){    
  for(int i=1;i<=5;i++){    
   try{    
    Thread.sleep(500);    
   }catch(Exception e){System.out.println(e);}    
  System.out.println(i);    
  }    
 }    
public static void main(String args[]){    
 TestJoinMethod1 t1=new TestJoinMethod1();    
 TestJoinMethod1 t2=new TestJoinMethod1();    
 TestJoinMethod1 t3=new TestJoinMethod1();    
 t1.start();    
 try{    
  t1.join();    
 }catch(Exception e){System.out.println(e);}    
    
 t2.start();    
 t3.start();    
 }    
}    
Output:

       1
       2
       3
       4
       5
       1
       1
       2
       2
       3
       3
       4
       4
       5
       5
Question: Can you give me a join(long miliseconds) Method Example?
Answer: Filename: TestJoinMethod2.jav

class TestJoinMethod2 extends Thread{    
 public void run(){    
  for(int i=1;i<=5;i++){    
   try{    
    Thread.sleep(500);    
   }catch(Exception e){System.out.println(e);}    
  System.out.println(i);    
  }    
 }    
public static void main(String args[]){    
 TestJoinMethod2 t1=new TestJoinMethod2();    
 TestJoinMethod2 t2=new TestJoinMethod2();    
 TestJoinMethod2 t3=new TestJoinMethod2();    
 t1.start();    
 try{    
  t1.join(1500);    
 }catch(Exception e){System.out.println(e);}    
    
 t2.start();    
 t3.start();    
 }    
}    
Output:

	1
       2
       3
       1
       4
       1
       2
       5
       2
       3
       3
       4
       4
       5
       5
Question: How to Name a Thread?
Answer: The Thread class provides methods to change and get the name of a thread. By default, each thread has a name, i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using the setName() method. The syntax of setName() and getName() methods are given below:

public String getName(): is used to return the name of a thread.  
public void setName(String name): is used to change the name of a thread.
Question: Can you give me an Example of naming a thread : Using setName() Method?
Answer: FileName: TestMultiNaming1.java

class TestMultiNaming1 extends Thread{  
  public void run(){  
   System.out.println("running...");  
  }  
 public static void main(String args[]){  
  TestMultiNaming1 t1=new TestMultiNaming1();  
  TestMultiNaming1 t2=new TestMultiNaming1();  
  System.out.println("Name of t1:"+t1.getName());  
  System.out.println("Name of t2:"+t2.getName());  
   
  t1.start();  
  t2.start();  
  
  t1.setName("Sonoo Jaiswal");  
  System.out.println("After changing name of t1:"+t1.getName());  
 }  
}  

Output:

Name of t1:Thread-0
Name of t2:Thread-1
After changing name of t1:Sonoo Jaiswal
running...
running...
Question: Can you give me an Example of naming a thread : Without Using setName() Method?
Answer: One can also set the name of a thread at the time of the creation of a thread, without using the setName() method. Observe the following code.

FileName: ThreadNamingExample.java

// A Java program that shows how one can   
// set the name of a thread at the time  
// of creation of the thread  
  
// import statement  
import java.io.*;  
  
// The ThreadNameClass is the child class of the class Thread  
class ThreadName extends Thread  
{  
  
// constructor of the class  
ThreadName(String threadName)  
{  
// invoking the constructor of  
// the superclass, which is Thread class.  
super(threadName);  
}  
  
// overriding the method run()  
public void run()  
{  
System.out.println(" The thread is executing....");  
}  
}  
  
public class ThreadNamingExample  
{  
// main method  
public static void main (String argvs[])  
{  
// creating two threads and settting their name  
// using the contructor of the class  
ThreadName th1 = new ThreadName("JavaTpoint1");  
ThreadName th2 = new ThreadName("JavaTpoint2");  
  
// invoking the getName() method to get the names  
// of the thread created above  
System.out.println("Thread - 1: " + th1.getName());  
System.out.println("Thread - 2: " + th2.getName());  
  
  
// invoking the start() method on both the threads  
th1.start();  
th2.start();  
}  
}  
Output:

Thread - 1: JavaTpoint1
Thread - 2: JavaTpoint2
 The thread is executing....
 The thread is executing....
Question: What is Current Thread?
Answer: The currentThread() method returns a reference of the currently executing thread.

public static Thread currentThread()
Question: Can you give me an Example of currentThread() method?
Answer: FileName: TestMultiNaming2.java

class TestMultiNaming2 extends Thread{  
 public void run(){  
  System.out.println(Thread.currentThread().getName());  
 }  
 public static void main(String args[]){  
  TestMultiNaming2 t1=new TestMultiNaming2();  
  TestMultiNaming2 t2=new TestMultiNaming2();  
  
  t1.start();  
  t2.start();  
 }  
}  

Output:

Thread-0
Thread-1
Question: What is the Priority of a Thread (Thread Priority)?
Answer: Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java program.
Question: What is Setter & Getter Method of Thread Priority?
Answer: Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).
Question: What are the 3 constants defined in Thread class?
Answer: 1.public static int MIN_PRIORITY
2.public static int NORM_PRIORITY
3.public static int MAX_PRIORITY
Question: Can you give me an Example of priority of a Thread?
Answer: FileName: ThreadPriorityExample.java

// Importing the required classes  
import java.lang.*;  
  
public class ThreadPriorityExample extends Thread   
{  
  
// Method 1  
// Whenever the start() method is called by a thread  
// the run() method is invoked  
public void run()  
{  
// the print statement  
System.out.println("Inside the run() method");  
}  
  
// the main method  
public static void main(String argvs[])  
{  
// Creating threads with the help of ThreadPriorityExample class  
ThreadPriorityExample th1 = new ThreadPriorityExample();  
ThreadPriorityExample th2 = new ThreadPriorityExample();  
ThreadPriorityExample th3 = new ThreadPriorityExample();  
  
// We did not mention the priority of the thread.  
// Therefore, the priorities of the thread is 5, the default value  
  
// 1st Thread  
// Displaying the priority of the thread  
// using the getPriority() method  
System.out.println("Priority of the thread th1 is : " + th1.getPriority());  
  
// 2nd Thread   
// Display the priority of the thread  
System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
  
// 3rd Thread   
// // Display the priority of the thread  
System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
  
// Setting priorities of above threads by  
// passing integer arguments  
th1.setPriority(6);  
th2.setPriority(3);  
th3.setPriority(9);  
  
// 6  
System.out.println("Priority of the thread th1 is : " + th1.getPriority());  
  
// 3  
System.out.println("Priority of the thread th2 is : " + th2.getPriority());  
  
// 9  
System.out.println("Priority of the thread th3 is : " + th3.getPriority());  
  
// Main thread  
  
// Displaying name of the currently executing thread   
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());  
  
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
  
// Priority of the main thread is 10 now  
Thread.currentThread().setPriority(10);  
  
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
}  
}  
Output:

Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10
Question: Can you give me an Example of IllegalArgumentException?
Answer: We know that if the value of the parameter newPriority of the method getPriority() goes out of the range (1 to 10), then we get the IllegalArgumentException. Let's observe the same with the help of an example.

FileName: IllegalArgumentException.java

// importing the java.lang package  
import java.lang.*;  
  
public class IllegalArgumentException extends Thread   
{  
  
// the main method  
public static void main(String argvs[])  
{  
  
// Now, priority of the main thread is set to 17, which is greater than 10  
Thread.currentThread().setPriority(17);  
  
// The current thread is retrieved  
// using the currentThread() method  
  
// displaying the main thread priority  
// using the getPriority() method of the Thread class  
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());  
  
}  
}  
When we execute the above program, we get the following exception:

Exception in thread "main" java.lang.IllegalArgumentException
	at java.base/java.lang.Thread.setPriority(Thread.java:1141)
	at IllegalArgumentException.main(IllegalArgumentException.java:12)
Question: What is Daemon Thread in Java?
Answer: Daemon thread in Java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes, memory usage, running threads etc.
Question: What are the Points to remember for Daemon Thread in Java?
Answer: -It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
-Its life depends on user threads.
-It is a low priority thread.
Question: Why JVM terminates the daemon thread if there is no user thread?
Answer: The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.
Question: What are the Methods for Java Daemon thread by Thread class?
Answer: Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.

Method: public void setDaemon(boolean status)
Description: is used to mark the current thread as daemon thread or user thread.

Method: public boolean isDaemon()
Description: is used to check that current is daemon.
Question: Can you give me a Simple example of Daemon thread in java?
Answer: public class TestDaemonThread1 extends Thread{  
 public void run(){  
  if(Thread.currentThread().isDaemon()){//checking for daemon thread  
   System.out.println("daemon thread work");  
  }  
  else{  
  System.out.println("user thread work");  
 }  
 }  
 public static void main(String[] args){  
  TestDaemonThread1 t1=new TestDaemonThread1();//creating thread  
  TestDaemonThread1 t2=new TestDaemonThread1();  
  TestDaemonThread1 t3=new TestDaemonThread1();  
  
  t1.setDaemon(true);//now t1 is daemon thread  
    
  t1.start();//starting threads  
  t2.start();  
  t3.start();  
 }  
}  

Output:

daemon thread work
user thread work
user thread work
Question: What is Java Thread Pool?
Answer: Java Thread pool represents a group of worker threads that are waiting for the job and reused many times.

In the case of a thread pool, a group of fixed-size threads is created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, the thread is contained in the thread pool again.
Question: What are the Thread Pool Methods?
Answer: newFixedThreadPool(int s): The method creates a thread pool of the fixed size s.

newCachedThreadPool(): The method creates a new thread pool that creates the new threads when needed but will still use the previously created thread whenever they are available to use.

newSingleThreadExecutor(): The method creates a new thread.
Question: What is the Advantage of Java Thread Pool?
Answer: Better performance It saves time because there is no need to create a new thread.
Question: Can you give me an Example of Java Thread Pool?
Answer: Let's see a simple example of the Java thread pool using ExecutorService and Executors.

File: WorkerThread.java

import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
class WorkerThread implements Runnable {  
    private String message;  
    public WorkerThread(String s){  
        this.message=s;  
    }  
     public void run() {  
        System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);  
        processmessage();//call processmessage method that sleeps the thread for 2 seconds  
        System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name  
    }  
    private void processmessage() {  
        try {  Thread.sleep(2000);  } catch (InterruptedException e) { e.printStackTrace(); }  
    }  
}  
File: TestThreadPool.java

public class TestThreadPool {  
     public static void main(String[] args) {  
        ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads  
        for (int i = 0; i < 10; i++) {  
            Runnable worker = new WorkerThread("" + i);  
            executor.execute(worker);//calling execute method of ExecutorService  
          }  
        executor.shutdown();  
        while (!executor.isTerminated()) {   }  
  
        System.out.println("Finished all threads");  
    }  
 }  
Output:

pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads
Question: What are the Risks involved in Thread Pools?
Answer: The following are the risk involved in the thread pools.

Deadlock: It is a known fact that deadlock can come in any program that involves multithreading, and a thread pool introduces another scenario of deadlock. Consider a scenario where all the threads that are executing are waiting for the results from the threads that are blocked and waiting in the queue because of the non-availability of threads for the execution.

Thread Leakage: Leakage of threads occurs when a thread is being removed from the pool to execute a task but is not returning to it after the completion of the task. For example, when a thread throws the exception and the pool class is not able to catch this exception, then the thread exits and reduces the thread pool size by 1. If the same thing repeats a number of times, then there are fair chances that the pool will become empty, and hence, there are no threads available in the pool for executing other requests.

Resource Thrashing: A lot of time is wasted in context switching among threads when the size of the thread pool is very large. Whenever there are more threads than the optimal number may cause the starvation problem, and it leads to resource thrashing.