Lab 8: Multi-Threading in Java

Lab 8: Multi-Threading in Java

LAB OBJECTIVE: Understanding about simultaneous execution of two or more parts of a program to maximum utilize the CPU time.

Multi-Tasking

Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one thing at a time. For example, that streaming audio application must simultaneously read the digital audio off the network, decompress it, manage playback, and update its display. Even the word processor should always be ready to respond to keyboard and mouse events, no matter how busy it is reformatting text or updating the display. Software that can do such things is known as concurrent software.

Multi- tasking via Multi-Threading

Multi-threading in java is a process of executing multiple threads simultaneously. There are two ways to create a thread:

  1. By extending Thread class
  2. By implementing the Runnable interface

Case 0: Implementing   Thread by  Extending Thread Class

Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.

class Multi extends Thread{  
    public void run(){    //used to perform action for a thread.
        System.out.println("Hey look thread is running...");  
    }  
    public static void main(String args[]){  
        Multi t1=new Multi();    // Creating a object of thread class
        t1.start();  // to start tread 
     }  
}  

/*
Output: 
             F:\coreJAVA\13Multithreading>javac Multi.java
             F:\coreJAVA\13Multithreading>java Multi
             Hey look thread is running...

*/

Starting and Defining a Thread

Case 0: Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

// save as HelloRunnable.java
public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}
/*
Output: 
             F:\coreJAVA\13Multithreading>javac HelloRunnable.java
             F:\coreJAVA\13Multithreading>java HelloRunnable
             Hello from a thread!

*/

Case 1: Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example:

// save as HelloThread.java
public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}
/*
Output: 
             F:\coreJAVA\13Multithreading>javac HelloThread.java
             F:\coreJAVA\13Multithreading>java HelloThread
             Hello from a thread!

*/

Note : Notice that both examples invoke Thread.start in order to start the new thread.

Which of these idioms should you use?

The first idiom, which employs a Runnable object, is more general because the Runnable object can subclass a class other than Thread. The second idiom is easier to use in simple applications but is limited by the fact that your task class must be a descendant of Thread.

Pausing Execution with sleep()

Thread.sleepcauses the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

// save as 
/*
The SleepMessages example uses sleep to print messages at four-second intervals:
/*
public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0; i < importantInfo.length; i++) {
             //Pause for 4 seconds
             try {
                 Thread.sleep(4000);
             } catch (InterruptedException e) {
             // We've been interrupted: no more messages.
        }
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}
/*
Output: 
             F:\coreJAVA\13Multithreading>javac SleepMessages .java
             F:\coreJAVA\13Multithreading>java SleepMessages 
             Mares eat oats,
             Does eat oats,
             Little lambs eat ivy,
             A kid will eat ivy too

*/