This Lesson Details The Reasons Why Threads Exist and What Bene T Do They Provide. We Also Discuss The Problems That Come With Threads
This Lesson Details The Reasons Why Threads Exist and What Bene T Do They Provide. We Also Discuss The Problems That Come With Threads
This lesson details the reasons why threads exist and what bene t do they provide. We also discuss the problems
that come with threads.
Introduction
Threads like most computer science concepts aren't physical objects. The
closest tangible manifestation of threads can be seen in a debugger. The
screen-shot below, shows the threads of our program suspended in the
debugger.
code files and click save, that clicking of the button will initiate a
workflow which will cause bytes to be written out to the underlying
physical disk. However, IO is an expensive operation, and the CPU will be
idle while bytes are being written out to the disk.
Whilst IO takes place, the idle CPU could work on something useful and
here is where threads come in - the IO thread is switched out and the UI
thread gets scheduled on the CPU so that if you click elsewhere on the
screen, your IDE is still responsive and does not appear hung or frozen.
Threads can give the illusion of multitasking even though at any given
point in time the CPU is executing only one thread. Each thread gets a
slice of time on the CPU and then gets switched out either because it
initiates a task which requires waiting and not utilizing the CPU or it
completes its time slot on the CPU. There are much more nuances and
intricacies on how thread scheduling works but what we just described,
forms the basis of it.
Bene ts of Threads
class Demonstration {
public static void main( String args[] ) throws InterruptedException {
SumUpExample.runTest();
}
}
class SumUpExample {
long startRange;
long endRange;
long counter = 0;
static long MAX_NUM = Integer.MAX_VALUE;
s2.add();
});
t1.start();
t2.start();
t1.join();
t2.join();
oneThread();
twoThreads();
}
}
In my run, I see the two threads scenario run within 652 milliseconds
whereas the single thread scenario runs in 886 milliseconds. You may
observe different numbers but the time taken by two threads would
always be less than the time taken by a single thread. The performance
gains can be many folds depending on the availability of multiple CPUs
and the nature of the problem being solved. However, there will always
be problems that don't yield well to a multi-threaded approach and may
very well be solved efficiently using a single thread.
1. Usually very hard to find bugs, some that may only rear head in
production environments