Threads in real world
Everybody in this world is performing one duty or the other.The duties, we perform, are kind of functional activity. Let us take an example of traditional family environment, generally husband involves in managing the finance (to maintain day to day expenses) and wife involves in household activities.
If we consider wife as a process, which performs multiple task like maintaining household activities, performing social activities, attending parents meet in school etc. The housewife takes the help of domestic helper, to perform certain tasks, which can be thought of thread. The domestic helper performs the fixed set of duties. The domestic helper make use of resources provided by house wife like vacuum cleaner, dish cleaner etc. After completing its activity helper goes away. The logical flow for is as follows:
- House wife looks out for the domestic helper.
- House wife assigns the task to domestic helper.
- Helper start the activity like cooking or cleaning.
- Helper complete the task(s).
- Helper goes away.
Analogy to Computer world:
In computer world, We creates the helper in the form of thread. Threads are dedicated functional/programming block, which gets executed by JVM to perform fixed set of task(s). We generally write the task inside the run method. The flow for thread execution is as follow
- Create the thread
- Write functionality inside a thread function.
- Thread execute its functionality (code in run method)
- Thread finished the execution.
- Thread completes it life cycle. (Thread release all the resources which was allocated to it)
Thread is a dedicated task, which can be performed independently. We create threads to perform dedicated task. Once the task is over, thread completes its life cycle.
Thread in java vs Thread in other languages C++, C# or C?
Threads are not bind to programming language. Threads uses system resources i.e. threads are typically related to operating system. The means to create thread(s), are different across programming languages but at the end of day, threads uses system resource.