Multithreading is a process that allows a multitasking
operating system to work on different portions, i.e., threads of a single
application smoothly. In other words, it can be described as a form of
parallelism where multiple threads can run in a concurrent manner.
Java supports programming for multitasking environment where
the CPU can perform different tasks simultaneously. The multitasking environment
can execute in two ways.
·
Process based multitasking
·
Thread based multitasking
Process based multitasking – A process is a program which is
currently acquiring the CPU time and, hence, it is the currently executing the program.
The process based multitasking can execute two different processes
simultaneously where the processes are running under different locations. For
example, we can write some text using editor, at the same time some other
software can play music.
Thread based multitasking – Thread is the smallest unit of
dispatchable codes. In a thread based multitasking environment, one program can
perform two different tasks. Therefore, we can say that two different tasks are
executing. For example, we can print a word document at the same time we can do
some typing.
The threading concept says that the different blocks of the
same program can be executed concurrently. In Java, for implementing threading,
there is a built-in class called Thread. There are various methods supported by
Thread class.
·
setName() – It takes a string argument and assigns it as the name
of the thread.
·
getName() – It returns a string which indicates the name of the
thread though it does not take any argument.
·
sleep() – It accepts an argument of long integer type and it
tells the thread to wait for certain milliseconds.
·
isAlive() – It determines whether a thread has completed its
execution or not. It returns true if the thread is still executing.
·
join() – This function tells a thread to wait for completion of
another thread.
·
start() – It invokes the threads or starts the thread.
·
run() – To run a thread, we need this. It contains the codes
which are executed when a thread is running.