The process-based multitasking which allows a computer to run several programs at the same time, is mostly a function of the operating system.
The thread-based multitasking is more involved with the language-level support. Because one process can have several threads of execution.
However, many languages have no bulit-in support for multi-threading. To achieve the target, the programer has to reply on OS functions to create, begin, synchronize and end threads. It could be a nightmare, and the code won't be portable also.
Java has a easy-to-use built-in multithreading model. We can regard a program as a collection of parallel tasks (threads) that interact with one another.
The java.lang.Thread class is for creating and controlling threads.
First of all, we need create a subclass of Thread that include a run method.
- The code within the run method performs the thread's task.
- Each instantiation of the subclass corresponds to a single thread.
The thread is implicitly stopped when the run method terminates.
We can also use the sleep method in the Thread class to cease execution for a desired time (ms).