What is Thread in Java?
- Threads consumes CPU in best possible manner, hence enables multiprocessing. Multi-threading reduces idle time of CPU which improves performance of application.
- Thread is light weight process.
- A thread class belongs to java.lang package.
- We can create multiple threads in java, even if we don’t create any Thread, one Thread at least do exist i.e. main thread.
- Multiple threads run parallel in java.
- Threads have their own stack.
- Advantage of Thread: Suppose one thread needs 10 minutes to get certain task, 10 threads used at a time could complete that task in 1 minute, because threads can run parallel.
What is difference between Process and Thread in Java?
One process can have multiple Threads,
Thread is subdivision of Process. One or more Threads runs in the context of process. Threads can execute any part of process. And same part of process can be executed by multiple Threads.
Processes have their own copy of the data segment of the parent process while Threads have direct access to the data segment of its process.
Processes have their own address while Threads share the address space of the process that created it.
Process creation needs whole lot of stuff to be done, we might need to copy whole parent process, but Thread can be easily created.
Processes can easily communicate with child processes but interprocess communication is difficult. While, Threads can easily communicate with other threads of the same process using wait () and notify() methods.
In process all threads share system resource like heap Memory etc. while Thread has its own stack.
Any change made to process does not affect child processes, but any change made to thread can affect the behavior of the other threads of the process.
Example to see where threads on are created on different processes and same process.
How to implement Threads in Java?
This is very basic threading question. Threads can be created in two ways i.e. byimplementing java.lang.Runnable interface or extending java.lang.Thread class and then extending run method.
Thread has its own variables and methods, it lives and dies on the heap. But a thread of execution is an individual process that has its own call stack. Thread are lightweight process in java.
Thread creation by implementingjava.lang.Runnableinterface.
We will create object of class which implements Runnable interface :
MyRunnable runnable=new MyRunnable();
Thread thread=new Thread(runnable);
And then create Thread object by calling constructor and passing reference of Runnable interface i.e. runnable object :
Thread thread=new Thread(runnable);
Does Thread implement their own Stack, if yes how?
Yes, Threads have their own stack. This is very interesting question, where interviewer tends to check your basic knowledge about how threads internally maintains their own stacks.
We should implement Runnable interface or extend Thread class. What are differences between implementing Runnable and extending Thread?
Well the answer is you must extend Thread only when you are looking to modify run() and other methods as well. If you are simply looking to modify only the run() method implementing Runnable is the best option (Runnable interface has only one abstract method i.e. run() ).Â
What are the differences between implementing Runnable interface and extending Thread class?
Multiple inheritances in not allowed in java: When we implement Runnable interface we can extend another class as well, but if we extend Thread class we cannot extend any other class because java does not allow multiple inheritance. So, same work is done by implementing Runnable and extending Thread but in case of implementing Runnable we are still left with option of extending some other class. So, it’s better to implement Runnable.
- Thread safety: When we implement Runnable interface, same object is shared amongst multiple threads, but when we extend Thread class each and every thread gets associated with new object.
- Inheritance (Implementing Runnable is lightweight operation): When we extend Thread unnecessary all Thread class features are inherited, but when we implement Runnable interface no extra feature are inherited, as Runnable only consists only of one abstract method i.e. run() method. So, implementing Runnable is lightweight operation.
- Coding to interface: Even java recommends coding to interface. So, we must implement Runnable rather than extending thread. Also, Thread class implements Runnable interface.
- Don’t extend unless you wanna modify fundamental behaviour of class, Runnable interface has only one abstract method i.e. run() : We must extend Thread only when you are looking to modify run() and other methods as well. If you are simply looking to modify only the run() method implementing Runnable is the best option (Runnable interface has only one abstract method i.e. run() ). We must not extend Thread class unless we’re looking to modify fundamental behaviour of Thread class.
- Flexibility in code when we implement Runnable: When we extend Thread first a fall all thread features are inherited and our class becomes direct subclass of Thread , so whatever action we are doing is in Thread class. But, when we implement Runnable we create a new thread and pass runnable object as parameter, we could pass runable object to executor Service & much more. So, we have more options when we implement Runnable and our code becomes more flexible.
- Executor Service: If we implement Runnable, we can start multiple thread created on runnable object with Executor Service (because we can start Runnable object with new threads), but not in the case when we extend Thread (because thread can be started only once).
How can you say Thread behaviour is unpredictable?
The solution to question is quite simple, Thread behaviour is unpredictable because execution of Threads depends on Thread scheduler, thread scheduler may have different implementation on different platforms like windows, unix etc. Same threading program may produce different output in subsequent executions even on same platform.
To achieve we are going to create 2 threads on same Runnable Object, create for loop in run() method and start both threads. There is no surety that which threads will complete first, both threads will enter anonymously in for loop.
When threads are not lightweight process in Java?
Threads are lightweight process only if threads of same process are executing concurrently. But if threads of different processes are executing concurrently then threads are heavy weight process.
How can you ensure all threads that started from main must end in order in which they started and also main should end in last?
Interviewers tend to know interviewees knowledge about Thread methods. So this is time to prove your point by answering correctly. We can use join() methodto ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for this thread to die. Calling join() method internally calls join(0);
DETAILED DESCRIPTION: Join() method – ensure all threads that started from main must end in order in which they started and also main should end in last. Types of join() method with programs- 10 salient features of join.
What is difference between starting thread with run() and start() method?
This is quite interesting question, it might confuse you a bit and at time may make you think is there really any difference between starting thread with run() and start() method.
When you call start () method, main thread internally calls run() method to start newly created Thread, so run() method is ultimately called by newly created thread.
When you call run() method main thread rather than starting run() method with newly thread it start run() method by itself.
What is significance of using Volatile keyword?
Java allows threads to access shared variables. As a rule, to ensure that shared variables are consistently updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that enforces mutual exclusion for those shared variables.
If a field is declared volatile, in that case the Java memory model ensures that all threads see a consistent value for the variable.