What is Multithreading and why does it Exist?
Let's take an example to understand this. Assume we need to compute a simple multi-step mathematical computation problem. ((2 + 5) * (6 + 4)). The computer is going to compute this in 3 steps:1). Find (2 + 5)
2). Find (6 + 4)
3). Lastly, multiply the results of steps 1 and 2.
Now let's assume each step takes exactly 1 unit of time, the above would be completed in 3 units of time. But what if two threads could be run simultaneously to solve the above problem?
When we used 2 threads, steps 1 and 2 will be performed simultaneously and then subsequently multiplied by each other once the result is found. the same computation that previously took 3 units of time would be completed in only 2 units of time — a saving of 33%.
Multithreading enables us to run multiple threads concurrently. For example, after you log in to your Instagram account, one thread will load the stories of the accounts you are following, whereas another thread updates your Instagram feed with the latest posts.
We can say multithreading improves the responsiveness of a system. Imagine what would happen if Instagram ran in a thread? It might take 10 seconds to fetch the stories, and after that, it might take another 10 seconds to fetch the posts. This might make Instagram completely unresponsive because it won't allow users to perform another operation till all the stories and posts are loading.
What is Thread in Java?
Thread in Java is a lightweight process and represents an independent path of execution. It's a way to take advantage of multiple CPUs available on a machine. By employing multiple threads we can speed up CPU-bound tasks.Let's assume that one thread takes 100 milliseconds to do a job, we can use 10 threads to reduce that task to 10 milliseconds. Java provides excellent support for multithreading at the language level, and it's also one of the strong selling points.
What is the difference between Thread and Process in Java?
- One process can contain multiple threads, which means the thread is a subset of the Process.
- Two processes run on different memory spaces, but all threads share the same memory space. Don't confuse this with stack memory, which is different for the different threads and used to store local data in that thread.
- Threads can directly communicate with other threads; whereas processes must use inter-process communication to communicate with sibling processes.
What is a daemon thread?
Daemon threads are sometimes referred to as "service" threads. These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. e.g: a daemon thread is provided by JVM, which is continuously running as the garbage collector thread.A few salient features of the daemon() threads:
- Daemon threads are scheduled by the Thread scheduler, only when the CPU is idle.
- Daemon threads are service-oriented threads, they serve all other threads.
- Daemon threads are created before user threads are created and die after all other user threads die.
- The priority of daemon threads is always 1 (MIN_PRIORITY).
- All the user-created threads are non-daemon threads.
- JVM can exit when only daemon threads exist in the system. When all non-daemon threads are terminated, the JVM simply abandons all remaining daemon threads.
- To check whether the thread is daemon or not, we can use isDaemon() method.
- To make any user method a daemon thread by setDaemon(boolean b)
- If setDaemon(boolean b) is called on the thread after calling the start() method then IllegalThreadStateException is thrown.
- We generally should not do any I/O in daemon threads, as they won't even be able to execute their final blocks and close the resources if abandoned.
- A child thread created from a daemon thread is also a daemon thread.
Thread d1 = new Thread(() -> System.out.println("Starting a daemon thread!"));
d1.setDaemon(true);
d1.start();
If we run the above code as a part of the main() method, the message 'Starting a daemon thread!' might not get printed. Because d1 is a daemon thread the main() thread would terminate before the daemon would get to the point of printing the message.
How do you implement Thread in Java?
There are two ways of implementing threading in Java :1) By extending java.lang.Thread class
2) By implementing java.lang.Runnable interface
Since the Thread class itself implements Runnable, we can override the run() method either by extending the Thread class or just implementing the Runnable interface.
We can also create threads by using the Callable interface or by using the Executor Framework (I will try to explain the Callable and Executor frameworks in the future).
What is the difference between the start() and run() methods of the Thread class?
When a program calls the start() method, a new Thread is created and code inside the run() method is executed in the new Thread. If we call the run() method directly, no new Thread will be created and code inside run() will be executed on the current Thread.Another difference between start and run methods in the Java thread is that we can not call the start() method twice on the thread object. Once started, the second call of start() will throw IllegalStateException in Java while you can call the run() method twice.
What is the purpose of activeCount(), currentThread(), and enumerate() methods?
public static int activeCount()
- activeCount() is a static method of the Thread class.
- It returns the number of active threads in the current thread's thread group.
- The value returned is only an estimate because the number of threads may change dynamically while this method traverses internal data structures.
- This method doesn't throw any exception.
- currentThread() is also a static method of the Thread class that returns a reference to the currently executing thread object.
- enumerate() is another static method present in the Thread class.
- This method copies into the specified array every active thread in the current thread's thread group and its subgroups. It calls the enumerate method of the current thread's thread group with the tarray argument.
- This method uses the activeCount method to get an estimate of how big the array should be. If the length of the array is too short to hold all the threads, the extra threads are silently ignored.
- enumerate() method can throw SecurityException, if a security manager exists and its checkAccess method doesn't allow the operation.
Also Check: Java Thread Interview Questions & Answers
If you enjoy our content and want to support us, please consider donating via gpay, phonepay or paytm on +91 9920600280. Also, I’d appreciate it if you’d buy me a coffee☕
Keep learning and growing!
-K Himaanshu Shuklaa..
thankj you for detailed explanantion sir
ReplyDelete