Multithreading
Multithreading
Multithreading
Bing
Multithreading is a feature that allows concurrent execution of two or more parts of a program for maximum
utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within
a process.
1. Extend the Thread class: We create a class that extends the java.lang.Thread class. This class
overrides the run() method available in the Thread class. A thread begins its life inside run() method.
We create an object of our new class and call start() method to start the execution of a thread.
2. Implement the Runnable Interface: We create a new class which implements java.lang.Runnable
interface and override run() method. Then we instantiate a Thread object and call start() method on
this object.
class Multithread {
public static void main(String[] args) {
int n = 8;
for (int i = 0; i < n; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
The primary purpose of multithreading is to provide simultaneous execution of two or more parts of a program
to make maximum use of CPU time. A multithreaded program contains two or more parts that can run
concurrently. Multithreading is mostly used in games, animation, etc.
Advantages of Multithreading:
1. It doesn’t block the user because threads are independent and you can perform multiple operations at the
same time.
2. You can perform many operations together, so it saves time.
3. Threads are independent, so it doesn’t affect other threads if an exception occurs in a single thread.
Please note that every class used as a thread must implement the Runnable interface and override its run()
method. Also, the Thread class is part of the java.lang package.