Why multithreading is important in programming? Discuss.
Multithreading is the ability to run multiple threads concurrently. Thus multithreaded programs can do many things at once. A thread is a separate unit of execution performing a particular task in a multithreaded program. A thread is implemented by a particular method in programming language such as Java. With multithreading, we can achieve multitasking. If we have multiple CPUs, then each thread of a program can run on different CPUs allowing parallelism. If we have only one CPU, then the threads take turns in their run and this context switching of threads takes less time than multiprocessing systems. For example, in word processors such as MS-Word, one thread may be receiving input, another thread may be performing grammar check, and another thread may be auto-saving the data, and so on. While one thread is waiting, another thread is scheduled to run in single CPU systems. Further, in multithreading, all the threads of a program share the same memory space whereas if it has been multiprocessing system, then each process would have its own memory space. Thus, multithreading is important in programming for achieving multitasking and for optimizing resource use.
In the code example below, we have two threads Thread 1 and Thread2. Thread1 prints odd numbers from 1 to 10 after 1 second and Thread2 prints even numbers in the same range after 1⁄2 second.
class Thread1 extends Thread {
@Override
public void run() {
try {
for (int i = 1; i <= 10; i = i + 2) {
Thread.sleep(1000);
System.out.println(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Exiting Thread1");
}
}
class Thread2 extends Thread {
@Override
public void run() {
try {
for (int i = 2; i <= 10; i = i + 2) {
Thread.sleep(500);
System.out.println(i);
}
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Exiting Thread2");
}
}
public class ThreadTest {
public static void main(String[] a) {
Thread1 t1 = new Thread1();
t1.start();
Thread2 t2 = new Thread2();
t2.start();
}
}
Comments
Post a Comment