Q1. How Java Thread is different than Regular Java Objects?

Ans: Java Thread are same as any regular Java Objects. They are instance of java.lang.Thread class.  However, they have extra capabilities, whatever you written in run() method of Thread class instance will be executed in a separate thread.

Q2. What are all the ways by which a new Thread can be created?

Ans: There are mainly two ways to create new Thread. However, both method requires Thread class.

Approach 1: Using Thread Class, Create an Instance of Thread Class

Thread threadInstance = new Thread(); // Create Instance of a thread class

threadInstance.start(); // Starting thread

 

Approach 2: Using Runnable interface:  In this approach we need to Implement Runnable interface.

public class TestRunnable implements Runnable {

public void run(){}

}

 

Thread threadInstance = new Thread(new TestRunnable() ); // Create Instance of a thread class

threadInstance.start(); // Starting thread, it will execute run method of TestRunnable object

 

Q3. When we should use, approach in which we are sub-classing the Thread (Important)?

Ans: There is no particular rule for defining which approach is better.  However, it is recommended when you need long running threads e.g. ThreadPool (Having like 10 of threads, pre-created). We should use Thread sub-classing approach. Hence, we have 10 long running threads and their responsibility is to run the task submitted to them.

Let’s take an example:  You are having a 10,000 small test files. Now you want to calculate number of words in each file. In this case, what we are going to do, create 10,000 tasks (not 10000 threads). We will submit these 10,000 tasks to ThreadPool (which has 10 threads). Each thread will run 1000 tasks. Hence, using only 10 threads we have completed our entire word count of 10,000 files. These types of BigData Problems can be easily solved using Hadoop Framework (visit: www.HadoopExam.com)

Q4. When should we use approach for Runnable interface?

Ans: As mentioned in above question, we should use Thread sub-classing approach, when we need ThreadPool (Long running Threads). And the tasks mentioned in above example should be Runnable. Hence, we will create 10,000 Runnable instances and submitting them to ThreadPool, and each thread from ThreadPool will execute the Runnable instance.

 

Q5. What happen if we call run() method directly on thread class instead of calling start() method on thread class instance?

Ans: Below code shows, how to start a new thread

Thread threadInstance = new Thread(); // Create Instance of a thread class

threadInstance.start(); // Starting thread

 

Now if we call threadInstance.run() directly, than it will not create a new Thread and execution will be part of same thread which called run() method. Hence, it is must to call start() method.