Advanced Java Programming - Old Questions
9. Why multithreading is important in programming? Discuss.
The process of executing multiple threads simultaneously is known as multithreading. The main purpose of multithreading is to provide simultaneous execution of two or more parts of a program to maximum utilize the CPU time. A multithreaded program contains two or more parts that can run concurrently. Each such part of a program called thread.
Multithreading is important due to following reasons:
- It doesn't block the user because threads are independent and we can perform multiple operations at the same time.
- We can perform many operations together, so it saves time.
- Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
Example:
Program to create two threads. The first thread should print numbers from 1 to 10 at intervals of 0.5 second and the second thread should print numbers from 11 to 20 at the interval of 1 second.
class First extends Thread
{
@Override
public void run()
{
for (int i=1; i<=10; i++)
{
System.out.println(i);
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
class Second extends Thread
{
@Override
public void run()
{
for (int i=11; i<=20; i++)
{
System.out.println(i);
try{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
}
public class ThreadInterval
{
public static void main(String[] args)
{
Thread first = new First();
Thread second= new Second();
first.start();
second.start();
}
}