Follow @abushalihu Abu The Geek: December 2011

Thursday, December 15, 2011

Threads in Java (level: Beginner with good knowledge in Java program)

      I did not think that there is no most interesting and/or difficult features available in Java other than Thread like C had pointers. Any Java developer who is really unaware of threads also had written thread programs!. Trust me, I am not lying. It is true!.

Normally, every Java program starts its execution by a thread called the Main thread. So what does a thread mean?

Thread
-------------
A Thread is a separate path of execution in a process or program. More specifically a threads job is to get the CPU cycles (probably when the CPU is idle) to execute some set of codes of a program for a while or long.

Main Uses of Threads (These three bullets must be in your mind when thinking about threads)
---------------------------
1.    To utilize the CPU cycles as much as possible
2.    To introduce the Asynchronous behaviour
3.    To have Parallellism or treat a single processor as Multiprocessor

Multithreading
--------------------
In a single threaded program when you run any of your program many time the CPU could be in idle state. For example your program might be blocked for any input from the User, File, Socket or even some other program. In such a time the CPU is idle. So it is better to have any other threads to fully utilize the CPU's idle time. By doing so, we can reduce the CPU's idle time.

Multithreading is a specialized form of multitasking. In multitasking more than one procesess could run concurrenty. Multithreading on the other hand that more than one threads could run on a single process. Some differences are there between them. In multithreading two threads shares the same process meaning that threads are running on the same address space.

How to create a Thread
------------------------------
There are two categories to create threads.

1.    By Implementing Runnable Interface
2.    By Extending Thread Class

Runnable having only one method called run method. This is the method from which a thread starts its execution.
Thread class having some usefull methods such as getName(), currentThread(), start(), stop(), sleep() and etc.

Sample program (Implementing Runnable Interface)
-----------------------------------------------------------------
class ConzolePrinter implements Runnable {
private String printMessage;

ConzolePrinter(String text) {
    printMessage = text;
}

//Threads entry point.
public void run() {
    print(printMessage);
}

public void print(String text) {
    for(int i=0; i < 5; i++) {
        System.out.println("Text = " + text + " Printed by " + Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch(InterruptedException e) {
            System.err.println("Thread Interrupted " + e +" on thread "+ Thread.currentThread().getName());
        }
    }
    System.out.println(Thread.currentThread().getName() +" Exiting...");
}

public static void main(String args[]) throws Exception {

Runnable printerA = new ConzolePrinter("Hello");
Runnable printerB = new ConzolePrinter("World!");

Thread childThreadA = new Thread(printerA, "Thread-A");        // creating a child thread.
childThreadA.start();                        // starting a thread

Thread childThreadB = new Thread(printerB, "Thread-B");
childThreadB.start();

Thread mainThread = Thread.currentThread();        // returns currently executing thread. in this case it is main thread since it is main method.
mainThread.sleep(10000);                    // Sleeping main thread for 10 seconds to wait for the child threads to complete.
System.out.println(mainThread.getName() +" Exiting...");
}
}


Program Explanation
--------------------------
The ConzolePrinter class implements Runnable and overrides its run method and ConzolePrinter have its own method print to print a message into the console.

The main method creates two ConzolePrinter objects with the printMessage as argument. Two child threads are created namely childThreadA and childThreadB with the Runnable object as argument.

The two child threads get started by calling its start method. When calling start method of a thread the JVM will invoke the run method of the threads Runnable object.

The print method print a message for 5 times. For every print it sleeps the current thread for 1 second to enforce asynchronous execution behaviour. The main thread sleeps for 10 seconds for the two child threads to finish its task.

Exercise:
-------------
You try the same above program by extending a Thread class.

Note: I will be updating more on Threads as much as I learn from today onwards .