Print Hello World! from separate thread other main thread. A concept of Multi-threading and Concurrency.
Threads are like workers that help in executing and carrying out processes/tasks in the cores of CPUs. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Concurrency is the ability of a single-core processor to context-switch between several processes (program in execution) and execute them. In actual sense, only one task is running at a unit time.
Parallelism is the ability of a multi-core processor to context-switch between processes in every core (brain/unit of execution) and henceforth carry out multiple tasks simultaneously.
run() method executes tasks in the same previous thread.
start() method executes tasks in newly created threads.
In main() method, main thread executes all instructions. To print anything from a separate thread, we actually first have to focus on the task we want to do.
- Create a separate class for the task.
- Implement Runnable Interface.
- Override/Implement its run() method that takes no param and returns nothing (void).
- Then, create the object of the custom class inside main class's main() method.
- Create the object of the Thread class same there and pass the custom class's object inside that of Thread's.
- Finally, write thread.start(); to spawn a new thread and execute the task desired in that separate thread.