Easy approach to learn Threads
How to create a Thread?
Why Runnable is preferred over Thread?
- In OOPS, we extend the class to add new functionality, modify or improve functionality. If you are not making any modification on Thread functionality then we should go for Runnable Interface instead.
- Runnable represent a task. It can be executed by either plain Thread or Executor. With Runnable, we are separating the task from execution which is a flexible design.
- By extending the Thread, we have the overhead of inheriting all the Thread methods.
How to pause a thread?
How to interrupt a thread?
How to fetch the output from a Thread?
How do threads communicate?
How to protect shared data when it is accessed by multiple threads?
How to achieve thread safety?
- Minimize the sharing of objects between multiple threads.
- In case if the object is shared between multiple threads, multiple access should be restricted on the shared object. synchronize/Lock the shared object calls to ensure single access to the shared resource at any given point in time.
- Using immutable classes in multi-threaded environments is the best approach since the state of these instances cannot be changed.
Why Thread pool is better than a thread?
- Creation of thread is a costly process. Because it consumes time, CPU process (because OS has to create a separate process for the thread creation), and there is a limit on no. of threads created per JVM. So, creating a thread for a task is costlier than picking an already created thread from the thread pool.
- If we use a thread pool, we can reuse the fixed set of Threads(value of no. of threads is very much bounded) to do the tasks. Whereas in Threads, we have to create a thread for every incoming task which is unbounded.
- Thread pool uses threads which are already created. So, the task completion time is much quicker when compared to Thread.
Comments
Post a Comment