Monday, May 13, 2013

Java Multithreading Example



Multi-threading programming is conceptual paradigm for programming where we divide programs into two or more process which can run in parallel. With interactive network programs, we will find that there are many problems best solved concurrently. Before going see  code examples we will get to  know some thread concepts.

Multitasking and MultiThreading

In multi-tasking operating system tasks are known as heavy-weight process; in a multithreaded environment tasks are light weight process, or threads. The difference is that heavy weight process are in separate address space and should be thought of as different program running on the same system like Word Excel. Inter-process communication is expensive and limited .Context switching, changing the running process , is also heavy-weight. We usually only think about using one  of these programs at a time, even they are both running. Threads on the other hand share the same address space and co-operatively share the same heavy weight process. Inter-thread communication  is very light-weight and pervasive. Context switching is fast and an integral part of running any one program.

Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.

Creating Threads:

We can create thread  in a program using class Thread or implementing interface Runnable.

Lifecycle of a Thread
Java Threads
  1. New state � After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 
  2. Runnable (Ready-to-run) state � A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.  
  3. Running state � A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.
  4. Dead state � A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.

  1. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.
A simple program to explain the life cycle of thread

class ThreadDemo implements Runnable{
   Thread t;
 ThreadDemo(String s) {
 
 t=new Thread(this,s);
 t.start();//Ready to run
 }
 public void run() {//Running state
for(int i=0;i<5;i++) {
System.out.println("Thread Name :"+Thread.currentThread().getName());
 try{
 
Thread.sleep(1000);//Blocked
}catch(Exception e){}
}
}
//Dead state
}
public class RunnableThreadDemo1{
public static void main(String args[]){
System.out.println("Thread Name :"+Thread.currentThread().getName());
ThreadDemo m1=new ThreadDemo("My Thread 1");//New atate
ThreadDemo m2=new ThreadDemo("My Thread 2");
}
}

Synchronization
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors. E.g. synchronizing a function:
                              public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}

}

Synchronization
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors. E.g. synchronizing a function:
                              public synchronized void Method1 () {
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}

}
Messaging
Once our program is divided into several logical threaded parts, we have to define how these threads will communicate with each other. Java provide a clean way for two threads to talk to each other  via the wait() and notify() and notifyall() methods.

Thread Priorities
Thread priorities are defined as integers between 1 and 10. Ten is the highest priority. One is the lowest. The normal priority is five. Higher priority threads get more CPU time.
We can set a thread's priority with the setPriority(int priority) method.

No comments:

Post a Comment