Threads are the backbone of multithreading. We are living in the real world which in itself is caught on the web surrounded by lots of applications. With the advancement in technologies, we cannot achieve the speed required to run them simultaneously unless we introduce the concept of multi-tasking efficiently. It is achieved by the concept of thread.
Real-life Example of Java Multithreading :
Suppose you are using two tasks at a time on the computer, be it using Microsoft Word and listening to music. These two tasks are called processes . So you start typing in Word and at the same time start music app, this is called multitasking . Now you committed a mistake in a Word and spell check shows exception, this means Word is a process that is broken down into sub-processes. Now if a machine is dual-core then one process or task is been handled by one core and music is been handled by another core.
Multitasking is being achieved in two ways :
Multiprocessing : Process-based multitasking is a heavyweight process and occupies different address spaces in memory. Hence, while switching from one process to another, it will require some time be it very small, causing a lag because of switching. This happens as registers will be loaded in memory maps and the list will be updated.
Multithreading : Thread-based multitasking is a lightweight process and occupies the same address space. Hence, while switching cost of communication will be very less.
Below is the Lifecycle of a Thread been illustrated :
New : When a thread is just created.
Runnable : When a start() method is called over thread processed by the thread scheduler.
Case A: Can be a running thread
Case B: Can not be a running thread
Running : When it hits case 1 means the scheduler has selected it to be run the thread from runnable state to run state.
Blocked : When it hits case 2 meaning the scheduler has selected not to allow a thread to change state from runnable to run.
Terminated : When the run() method exits or stop() method gets called.
Top comments (0)