Multithreading Tutorial Java

Multithreading Tutorial Introduction

Comparative to other languages, multithreading is very easy and simple in Java and the credit goes to the portability nature and support of many Java API classes. The built-in support for threads is simple and straight so that any programmer can do with multithreading operations without confusion and special attention. Multithreading uses very effectively the microprocessor time by reducing its idle time. When the processor's idle time is reduced, the output of the programs comes earlier. Multithreading is a concept that should be supported by the operating system. Now-a-days, all operating systems support multithreading.

Multitasking, Multiprocessing and Multithreading

A program under execution is called a process. The general definition, a novice expresses, of multithreading is "performing multiple tasks at the same time is called multitasking ". This is very wrong and is the result of misunderstanding the concept. Every computer person knows well that microprocessor can execute only one instruction (task) at a time. That is, the earlier definition is going wrong somewhere else. This is the point of confusion about multithreading for everyone. Let us be clear about the concept. When a process is being executed, there may be an interruption, sometimes, for execution; for example, a keyboard input (scanf) may not be fed immediately. When not fed, the execution is halted (observe, the cursor will be blinking even for the whole day when the input is not given). Now the processor is free and idle. We can ask the microprocessor to do another process meantime. The processor obliges (as underlying OS supports multitasking). Now, two programs are under execution – the first one half the way completed and kept apart and the other being executed. When the second task (process) is over, if the input is ready, the control will be shifted to the first process and now the first process is executed completely. The result is output of both the programs is obtained earlier. All this is transparent (not known) to the user as context switching occurs at very fast speed.

Context Switching

"Shifting the microprocessor to execute another process when the first process is stopped its execution, is known as multitasking". Shifting between the processes is known as context switching. Do not shift unnecessarily when the first program is going smooth with its execution as context switching takes more time and performance looses. Shift only when a running process is stopped for some reason.

Putting multiple processors (say two) and feeding multiple processes simultaneously is known as multiprocessing and is a very rare phenomenon as multiple processors on desktop PCs is uncommon (only super computers have).

Multithreading is the Java's style of achieving multitasking. A single Java program can be divided into a number of threads and executed simultaneously while shifting between the threads when one stops its execution. The current tutorial discusses how to divide a Java program into multiple threads and how to execute them.

Three confusing terms: Simultaneously, concurrently, parallely

These terms are put here as they are again confusing. All means the same of doing multiple tasks at the same time. "At the same time" is a confusing idiom. Many processes may exist whose execution is stopped in the middle for some reason. Remember, only one can be active at any time. Which ever process is ready is called and executed. "Many" must be interpreted this way. It looks all at a time as context switching happens very fast (like cinema where a number of frames of images are run is such a speed, our eye cannot catch). Some more confusing terms are Preemptive and Cooperative Multitasking and Time-sharing . These terms are also discussed hereunder.

Preemptive multitasking and Time-sharing

At a given time, a number of processes may be getting executed on the CPU. CPU allocates a certain period of time, known as time-slice, for each process to execute. Each process is guaranteed of a time-slice. In preemptive multitasking , one process empties (forcibly evacuating) the other process for the time-slice period and thus every process definitely gets the CPU time. Thus, CPU time is shared by all the processes and is known as time sharing. Time sharing is a CPU architecture where CPU distributes its time equally to all the processes waiting for execution.

Preemptive and Cooperative Multitasking

In multitasking two types of algorithms exists – preemptive multitasking and cooperative multitasking. In preemptive multitasking, each process is allotted a certain period of time known as time slice. With time slices, the waiting processes get evenly all the CPU time and one process cannot hold the CPU time as long it wants. In contrary, in cooperative multitasking, one process can hold the microprocessor time as long as it would like. But the CPU is empowered to remove the process if the process does not utilize the time after holding it. Preemptive multitasking is supported by OS/2, UNIX, Windows NT etc. Cooperative multitasking is supported by Windows 3.1, UNIX, Windows NT etc.

Each type comes with its own advantages. When an immediate action or attention is required, like keyboard input or a button click, preemptive is preferred. The disadvantage of cooperative multitasking is, if designed poorly, it may hang the system.

Preemptive Scheduling and Non-preemptive Scheduling

For forcing the thread to vacate the microprocessor, two properties can be considered – priority and waiting time. In preemptive scheduling, a thread with more priority vacates the executing thread of low priority. That is, low-priority thread yields to the high-priority thread. In contrary, in non-preemptive scheduling, waiting time is considered and not priority. That is, the high-priority thread cannot relinquish a low-priority thread having more waiting time.

Memory Protection

With multitasking, the operating system must be built in a robust way. One ill-behaved process (a process that went out of control) may ruin or overwrite the other process data. This is a very serious condition. This is taken care by the OS in its architecture. Every process (or thread later) comes with its own execution area known as context area. One process is not allowed to access, by the OS, other process context area. To some extent, the programmer can also restrict this by issuing privileges to the processes. By issuing a low-privilege, the process may be restricted from accessing a particular memory region.

Pass your comments to improve the quality of this "Multithreading Tutorial Java".

12 thoughts on “Multithreading Tutorial Java”

  1. hello sir,
    I am not able to understand how the transfer of access is taking place in program when we are creating two threads and using isAlive() and join() method .
    the output iam getting is like this:
    mainthread executing
    childthread executing
    thread1 i:5
    thread1 is still Alive??true

    sir, please enlight this concept.

  2. abhishek thapliyal

    class NewThread implements Runnable {
    Thread t;
    NewThread() {
    // Create a new, second thread
    t = new Thread(this, “Demo Thread”);
    System.out.println(“Child thread: ” + t);
    t.start(); // Start the thread
    // This is the entry point for the second thread.
    public void run() {
    try {
    for(int i = 5; i > 0; i–) {
    System.out.println(“Child Thread: ” + i);
    } catch (InterruptedException e) {
    System.out.println(“Child interrupted.”);
    System.out.println(“Exiting child thread.”);
    class ThreadDemo {
    public static void main(String args[]) {
    new NewThread(); // create a new thread
    try {
    for(int i = 5; i > 0; i–) {
    System.out.println(“Main Thread: ” + i);
    } catch (InterruptedException e) {
    System.out.println(“Main thread interrupted.”);
    System.out.println(“Main thread exiting.”);

    here in line n 5 plz descibe the working of “this” in constructor NewThread()

    1. To know these, always refer Java API. The Thread API describes the constructor as follows:

      public java.lang.Thread(java.lang.Runnable, java.lang.String);

      So your this refers, the Runnable interface which you are implementing. It is like using this for ActionListener.

  3. Hello sir,
    in the interview i was asked that
    1) can we overload run method
    2) what happen if we did define run method in the class

  4. Shifting the microprocessor to execute another process when the first process is stopped its execution, is known as multithreading…. you say this

    but suppose i open VLC media player..
    then i use vedio and Audio …can these is multithreading.. ya Multiprocess

Leave a Comment

Your email address will not be published.