Translate the content to your language. Select your Language below.

Thursday, May 7, 2015

Multithreading

Multithreading is a conceptual coding where one program splitted into multiple subprograms, so called processes, and all these can be implemented at the same time. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a Thread, and each thread defines a separate path of execution. A process consists of the memory space allocated by the OS that can contain one or more threads. A thread can not exists on its own, it must be a part of process.

There are 2 different types of Multitasking. They are Processor Based and Thread Based.

Benefits of Multithreading:

1. It allows an user to run multiple programs at a time.
2. As exaplained above, a program can be splitted ito multiple subprograms which eventually increases the speed of an application.
3. Simultanious access to multiple applications.

Thread Life cycle is below:

New born State - When a thread object is created then it is called thread in new born status.
Runnable State - A thread is created and ready for executionand waiting for the processor availability.
Running State - A thread which is running currently.
Blocked State - A therad is prevented from entering into Runnable and Running states.
Dead State - Either a therad completes its task or is terminated during the execution.

Main Thread: A Java program starts up, one thread begins running which is called as Main Thread because it is the one executed when your program begins.
                  - Chaild threads are produced from main thread.
                  - Often it is the last thread to finish execution as it performs various shutdown operations.

Creatiung a Thread: Java defines two ways in which this can be accomplished.

                  - Type-1: Can be implemented by using Runnable interface
                  - Type-2: Can be implemented by using Thread class

           Type-1: To impletemt Runnable, subclass must implement run() method. Code that                              constitutes the new thread should keep inside run() method. run() method can call other                        methods, use other classes, and declare variables, just like Main thread.

                       Class thread1 implements Runnable {
                                  public void run() { System.out.println("Thread is Running");}
                                  public static void main(String args[]) {
                                           thread1 t1 = new thread1();
                                           Thread t = new Thread(t1);
                                           t.start();
                       }

           Type-2: To extend Thread, subclass must override run() method. 

                       Class thread1 implements Runnable {
                                  public void run() { System.out.println("Thread is Running");}
                                  public static void main(String args[]) {
                                           thread1 t1 = new thread1();
                                           t1.start();
                       }

Thread Methods:

1. public vois start() - Starts the thread in a separate path of execution, then invokes the run() method on Thread object.
2. public void run() - this method is invoked on the runnable object
3. public final void setName(String name) - Changes the anme of the Therad object. getName() is used to retrieve the thread name.
4. public final void setPriority(int priority) - sets the priority, but eventually its processors decision.
5. public final void setDaemon(boolean on) - TRUE denotes this Therad is a daemon therad.
6. public final void join(long millisec) - Current thread invokes this method on a second thread, causing the curent thread to block until the second thread terminates or the specified number of milliseconds passes.
7. public void interrupt() - Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8. public final boolean isAlive() - returns TRUE, if the thread is alive, before it runs to completion of the task.

Can we do Start a same thread multiple times?

It is not possible since a thread started once, it will never be started again.

Use of yield() method:- currently running thread to yield to any other threads which are waiting to be scheduled.

Class A extends Thread {
           public void run() {
              for(int i=1; i <= 5; i++) {
                    if(i == 2) yield();
                    System.out.println("Class A thread is running - Index: "+i);
              }
           }
}

Class B extends Thread {
           public void run() {
              for(int i=1; i <= 5; i++) {
                     System.out.println("Class B thread is running - Index: "+i);
              }
           }
}

Class test() {
           public static void main(String[] args) {
                   A a = new A();
                   B b = new B();
                   a.start();
                   b.start();
           }
}

Use of stop() method:- It kills the thread on execution.

Use of sleep() method:- It holds the thread from execution for specified amount of milli seconds.

Use of suspend() and resums() methods:- suspend() is useful when user wants to keep the thread execusion on hold and do not want to kill it. resumes() will revive the suspended thread.

Thread Priority:-
Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java priorities are in the range between MIN_PRIORITY [0] and MAX_PRIORITY [10]. If the priority is not set, by default thread is set to NORM_PRIORITY [5].

Threads having higher priority will be allocated processor time first than the threads with lower priority. However, therad priorities cannot guarantee the order oin which threads execute very much platform dependent.

Synchronization:-
When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one Thread at a time. This is called Thread Synchronization. Synchronized keyword used to block a bunch of code separately and it requires a lock which is associated with the object[class] to access.

Synchronized(object) {
-----
-----
}

As long as the method is synchronized, only thread will be allowed to access the method and until the execution is completed, no other thread can get access to the method.

Interthread Communication:-
Two or more synchronized threads communicating each other. Basically, current running thread paused and another thread enters into the method to be executed. This can be implemented by using the below methods.

wait(): It tells the current thread to pause and sleep until the second thread executes and calls notify().
notify(): It wakesup the first thread that called wait() on this object.
notifyAll(): It wakesup all the threads those called wait() on the same object. But the highest priority thread will get executed first.


---My sincere thanks to Achin Jain.

No comments:

Post a Comment