Java Concurrency Method basic example What is a Thread A Thread is a lightweight Process. Any Process can have multiple Threads running in it. For example in a web browser, we can have one thread Which will load the User Interface and we can have one more thread which will actually retrieve all the data that needs to be displayed in the User Interface. What is Multi-Threading Multithreading enables us to run Multiple Threads Concurrently. For example in a web browser, we can have on the thread which handles the User Interface and in Parallel, we can have one more thread which is fetching the data to be displayed. So multithreading improves the responsiveness of a System. What is Concurrency Concurrency in the Context of Threads enables us to run multiple Threads at the same time. Here Java concurrency example. But do the Threads Really run at the same time? Single Core Systems The Thread Scheduler provided by the JVM decides which Thread runs at any given time. The scheduler gives a small time slice to each Thread. So at any given time, we have an only thread which is actually running in the processor. But because of the time slicing, we get the feeling that multiple threads are running at the same time. Multi Core Systems Even in Multiple Core systems, the thread scheduler is involved. But since we have multiple cores, we can actually have multiple threads running at the exact same time. For example, if we have a dual-core system, then we can have 2 threads running at the exact same time. The first thread will run in the first core, and the second thread will run in the second core. Why is Multi-threading needed? Multithreading enables us to improve the responsiveness of a System. For example in a web browser, if everything ran in a single Thread, then the system will be completely unresponsive whenever data is being fetched to display. If it takes 10 seconds to fetch the data, then in that 10 seconds we won't be able to do anything else in the web browser like opening new tabs or even closing the web browser. So running different parts of a program in different threads concurrently helps improve the responsiveness of a system. How to write Multithreaded Programs in Java We can create Threads in java using the following Extending the Thread Class Implementing the Runnable Interface Implementing the Callable Interface By using the Executor Framework along with Runnable and Callable Tasks
Recommended Posts