Interview Questions on Java - Threads

1. What is Thread?

In java, Thread is a class which is used for multi threading purpose. Thread class is used to create and run the threads.

2. What is the Difference between multi processing and multi Threading?

In multi processing processor switch from one process to another.It is heavy weight process. multi threading happens in one process. it switch from one block to another block. It is light weight process.

3. What are the type of Threads.

There are two types of Threads.
1. User Thread : If Thread is Independent of parent Thread then it is User Thread.
2. Daemon Thread :
If Thread is Depending on parent Thread then it is Daemon Thread.

4. How many Threads create when a program is running?

3 Threads:
1. thread scheduler: schedules available times to all threads
2. garbage collector: used to remove abandoned objects.
3. main : executes main thread

5. How many ways are there to create the Thread.

Two ways:
1. By extending Thread class :
class A extends Thread {
public void run() { }
A a1 =new A();
a1.start();// it calls run method.

2. By implementing Runnable:
class A implements Runnable {
public void run() { }
A a1 = new A();
Thread t1 = new Thread(a1); t1.start();// calls run method

6. tell me some methods exist in Thread class?

1. run()
2. start();
3. sleep();
4. stop();
5. join();

7. What will happen when we call run() method instead of start()?

Code will be executed, but It will not act as a separate thread.

8. What is Synchronization?

Synchronization is the process of controlling multiple access to particular resource. In java synchronization is achieved by using synchronized keyword. synchronized keyword is used for methods and blocks.

9.Are wait(),notify() and notifyAll() available in Thread class?

No. They are available in Object class.But they are used for Thread Operation only. Because Inter process communication happens object wise not class wise.

10. What is the Difference between sleep() and wait()?

sleep() method is used to to stop executing for a given amount of time
wait() method is used to stop executing untill notify() method is called.

11. What is the use of join()?

If we use join() method then after fully executing of child thread main thread will execute.

12. What is the use of yield()?

yield() basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.