Saturday, July 26, 2014

Naming a Thread

Every Thread in a class has its own name like Thread-0, Thread – 1 and so on. We can also setthe name of Thread and get name of the Thread by two methods of Thread class as, public String getName() : return the name of the thread. public void setName(String name): set the name of the thread.

Example:

public class MyThread extends Thread{
 public void run(){
   try{
       for(int i=0;i<=5;i++){
         Thread.sleep(1000);
         System.out.println("Running thread is  = "+Thread.currentThread().getName());
       }
    }catch(InterruptedException ie){}
 }
 public static void main(String[] args){
     MyThread mt1 = new MyThread();
     MyThread mt2 = new MyThread();
     MyThread mt3 = new MyThread();
     mt1.start();
     mt2.start();
     mt3.start();
 }
}
Output: 

Running thread is  = Thread-0
Running thread is  = Thread-1
Running thread is  = Thread-2
Running thread is  = Thread-1
Running thread is  = Thread-2
Running thread is  = Thread-0
Running thread is  = Thread-2
Running thread is  = Thread-0......
Note: If you haven’t set the name of the thread the default name are Thread-0,Thread-1 so on..

public class MyThread extends Thread{
   public void run() {
        try {
            for (int i = 0; i <= 5; i++) {
                Thread.sleep(1000);
                System.out.println("Running thread is  = " + Thread.currentThread().getName();
            } // currentThread() returns current executing thread
        }
        catch (InterruptedException ie) {}
    }
    
    public static void main(String[] args){
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        MyThread mt3 = new MyThread();
        mt1.setName("One Thread");                                                           // to set the name of the thread
        mt2.setName("Two Thread");
        mt3.setName("Three Thread");
        mt1.start();
        mt2.start();
        mt3.start();
    } 
}

Sleeping a Thread

There are two overloaded methods of sleep in Thread class. The Thread object is sleep for specified amount of time. The sleep() method is a static method of class Thread. You use it in your code to "slow a thread down" by forcing it to go into a sleep mode before coming back to runnable. Notice that the sleep() method can throw a checked InterruptedException. Typically, you wrap calls to sleep() in a try/catch.

Example:

public class MyThread extends Thread{
    public void run(){
            try{
                for(int i=0;i<=5;i++){
            Thread.sleep(1000);
            System.out.println("Running here for.."+i);
                }
            }catch(InterruptedException ie){}
    }

    public static void main(String[] args){
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        MyThread mt3 = new MyThread();
        mt1.start();
        mt2.start();
        mt3.start();
    }
}
Output:

Running here for..0
Running here for..0
Running here for..0
Running here for..1
Running here for..1
Running here for..1
Running here for..2
Running here for..2
Running here for..2
Running here for..3
Running here for..3
Running here for..3
Running here for..4
Running here for..4
Running here for..4
Running here for..5
Running here for..5
Running here for..5

Few Points to note here,

Just keep in mind that the behaviour in the preceding output is still not guaranteed.

When a thread encounters a sleep call, it must go to sleep for at least the specified number of milliseconds (unless it is interrupted before its wake-up time, in which case it immediately throws the InterruptedException).

Just because a thread’s sleep() expires, and it wakes up, does not mean it will return to running! When a thread wakes up, it simply goes back to the runnable state. So the time specifi ed in sleep () is the minimum duration in which the thread won’t run.

Methods of Thread Class

  • public void run(): is used to perform action for a thread. 
  • public void start(): starts the execution of the thread.JVM calls the run() method on the thread. 
  • public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. 
  • public void join(): waits for a thread to die. 
  • public void join(long miliseconds): waits for a thread to die for the specified miliseconds. 
  • public int getPriority(): returns the priority of the thread. 
  • public int setPriority(int priority): changes the priority of the thread. 
  • public String getName(): returns the name of the thread. 
  • public void setName(String name): changes the name of the thread. 
  • public Thread currentThread(): returns the reference of currently executing thread. 
  • public int getId(): returns the id of the thread. 
  • public Thread.State getState(): returns the state of the thread. 
  • public boolean isAlive(): tests if the thread is alive. 
  • public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. 
  • public void suspend(): is used to suspend the thread(depricated).
  • public void resume(): is used to resume the suspended thread(depricated). 
  • public void stop(): is used to stop the thread(depricated). 
  • public boolean isDaemon(): tests if the thread is a daemon thread. 
  • public void setDaemon(boolean b): marks the thread as daemon or user thread. 
  • public void interrupt(): interrupts the thread. 
  • public boolean isInterrupted(): tests if the thread has been interrupted. 
  • public static boolean interrupted(): tests if the current thread has been interrupted. As we have seen that to start the execution under run() method we need to start the thread. 
But what, if we start the thread twice, it will throw IllegalThreadStateException.
Example:
public class MyThread extends Thread{
public void run(){
           System.out.println("Important job goes here..");
}
public static void main(String[] args){
          MyThread mt = new MyThread();
          mt.start();
          mt.start();
       }
}
Output:

Important job goes here..
Exception in thread "main" java.lang.IllegalThreadStateException
                at java.lang.Thread.start(Thread.java:638)
                at com.test.MyThread.main(MyThread.java:19)
What if we directly calls the run() method, like
public class MyThread extends Thread{
    public void run(){
        System.out.println("Important job goes here..");
    }
  
    public static void main(String[] args){
        MyThread mt = new MyThread();
        mt.run();
    }
}
Invoking run() method directly from the main thread the call goes to the current call stack rather than beginning a new call stack.

Thread Class

Let’s understand what we are doing here, we have four constructors of Thread class,
  • Thread()
  • Thread(Runnable target)
  • Thread(Runnable target, String name)
  • Thread(String name)
If you create a thread using the no-arg constructor, the thread will call its own run() method when it's time to start working. That's exactly what you want when you extend Thread, but when you use Runnable, you need to tell the new thread to use your run()method rather than its own. The Runnable you pass to the Thread constructor is called the target or the target Runnable.

As you can see in Thread class provided by java, the run() method is define as,
public void run() {
    if (target != null) {
           target.run();// That call your class run() method
    }    
}
At this point, all we have is the plain old java object of Thread class, It is not yet a thread of execution. To get an actual thread—a new call stack—we still have to start the thread.
To start a thread we write ,

t.start();

Few points to remember:
  • When a thread has been instantiated but not started (in other words, the start() method has not been invoked on the Thread instance), the thread is said to be in the new state.
  •  At this stage, the thread is not yet considered to be alive.
  •  Once the start() method is called, the thread is considered to be alive(even though the run() method may not have actually started executing yet).
  •  A thread is considered dead (no longer alive) after the run() method completes.
  •  When start() method called , a new thread of execution starts (with a new call stack).
  • The thread moves from the new state to the runnable state.
  • When the thread gets a chance to execute, its target run() method will run.

Creating Thread


There are 2 ways : 
  • By extending a Thread class
  • By implementing runnable interface.

Defining Thread: 
  • Extending Thread class
  • Overriding run() method

Example:
public class MyThread extends Thread{
    public void run(){
        System.out.println("Important job goes here..");
    }
  
    public static void main(String[] args){
        MyThread mt = new MyThread();
        mt.start();
    }
}
Output:

Important job goes here..

If you implement Runnable, instantiation is only slightly less simple. To have code run by a separate thread, you still need a Thread instance. But rather than combining both the thread and the job (the code in the run()method) into one class, you've split it into two classes—the Thread class for the thread-specific code and your Runnable implementation class for your job-that-should-be-run-by-a thread code. 

What is Thread in Java


So what exactly is a thread? In Java, "thread" means two different things:


  •  An instance of class java.lang.Thread
  •  A thread of execution

An instance of Thread is just like an object. Like any other object in Java, it has variables and  methods, and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack or, to think of it in reverse, one call stack per thread. The main() method, that starts the whole execution , runs in one thread, called the main thread.


Life Cycle of Thread (Thread State):

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The life cycle of a thread is maintained by JVM.

      

New : A thread begins its life cycle in the new state. It remains in this state until the start() method is called on it. It is also referred to as a born thread.

Runnable : The Thread is in runnable state when start() method is called. It will remain in the runnable state until the thread scheduler picks the thread into running state.

Running : This is the actual running state of the thread. It happens when thread scheduler chosen the thread from runnable state.

Blocked : This is the state when the thread is alive but not in the running state. When it resume it directly goes to the runnable state not in running state.

Terminated: thread is terminated or in dead state. This state arrives when run() method exits or completed the task.

Thread Scheduler :


  •  The thread scheduler is the part of the JVM,that decides which thread should run at any given moment, and also takes threads out of the run state.
  •  And it's the thread scheduler that decides which thread of all that are eligible(runnable state) will actually run.
  •  Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread.
  • The order in which runnable threads are chosen to run is not guaranteed.

Multithreading


Thread:

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. It shares the memory area of process. A single process might contain multiple threads . All threads within a process share the same state and same memory space, and can communicate with each other directly, because they share the same variables.

Multithreading:

To understand multithreading, we need to understand first the difference between process and Thread. A process is a program in execution. A process may be divided into a number of independent units known as threads. A thread is a dispatchable unit of work. Threads are light-weight processes within a process. A process is a collection of one or more threads and associated system resources.



    
Multitasking :

Multitasking of two or more processes is known as process-based multitasking. Multitasking of two or more threads is known as thread-based multitasking. Process-based multitasking is totally controlled by the operating system. But thread-based multitasking can be controlled by the programmer to some extent in a program.


Now, Multithreading is a process of executing multiple threads simultaneously, or you can say, Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). Java provides built-in support for multithreaded programming.                

Advantages of multithreading over multiprocessing :

  • Reduces the computation time.
  • Improves performance of an application.
  • Threads share the same address space so it saves the memory.
  • Context switching between threads is usually less expensive than between processes.
  • Cost of communication between threads is relatively low.

Friday, July 25, 2014

Nested Class

Nested Classes : 
One of the advantageous features of Java is the ability to define nested classes, i.e. classes within classes. In java classes are either top-level-classes (classed defined directly within a package) or nested classes (classes defined within top-level-classes). We use nested classes to logically group classes at one place so that it can be more readable and maintainable. It can also access private data members of the class.


Syntax :
Class Outer_class{
                Class Nested_class{
                // Body of nested class
}
}


What are the advantages of using nested classes :
  •  Imagine the case in which a certain class is being used only once from within another class, then there is no obvious need to add a clutter to the enclosing package by defining a top-level-class that will merely be used by only one another class.

  • Another very important advantage of having nested classes is the fact that nested classes will be able to access all the class members of their enclosing top-level-class (including the private member methods and variables).

  • Another advantage of this feature can be seen when developing event-based applications where action and event listeners can be defined as nested classes rather than having them as separate individual top-level-classes.    


  •       Code optimization as we need less code to write.



Types of Nested classes:


                              


Non- Static nested class : 

Non static nested classes are defined within the top-level-classes and they are bound by the scope of their enclosing class, non-static nested classes can have direct access into all of the members (even the private ones) of their enclosing class, on the other hand, the enclosing class doesn’t have any access to the members of the enclosed nested class.
·        

      Member Class : 

      A class that is declared inside a class but outside the method of the class. There are possible two ways through which we can access inner class are – from within a class and from outside the class.  


Example : (from within the class)


class OuterClass{
    private int x = 20;
   
    public class InnerClass{
        public void show(){
        System.out.println("x = "+x);
        }
    }
    public void display(){
        InnerClass inner = new InnerClass();
        inner.show();
    }   
    public static void main(String[] args){  
    OuterClass o = new OuterClass();
    o.display();
    }  
}



Example : (from outside the class)

class OuterClass{
    private int x = 20;
   
    public class InnerClass{
        public void show(){
        System.out.println("x = "+x);       }  
          }  
 }
class Test{  
    public static void main(String[] args){
    OuterClass o = new OuterClass();
        OuterClass.InnerClass inner = o.new InnerClass();
        inner.show();
    }  
}



·         Anonymous class :
      
      Java supports the definition of un-named inner classes, these classes differ from the inner classes in only one thing, which is that they are un-named, hence came the name “anonymous”. Anonymous classes can have direct access to all of the class members of the top-level-class in which they are defined.

Example : (using abstract class)

abstract class Person{
    abstract void show();
}
class NewClass{  
    public static void main(String[] args){
        Person p = new Person() {

            @Override
            public void show() {
                System.out.println("I am in Show method");
            }
        };       
        p.show();
    }  
}



Example : (using interface)

interface Person{
    void show();
}
class NewClass{  
    public static void main(String[] args){
        Person p = new Person() {

            @Override
            public void show() {
                System.out.println("I am in Show method");
            }
        };       
        p.show();
    }  
}



      Local Class :
   
       Local inner class is a class which is created inside a method body. If you want to access the local class you always need to instantiate inside the method only. It can only access final member of the class .


Example:

public class Test{
    private int var_data = 30;
    void display(){
        class Local_Class{
            public void msg(){
                System.out.println(var_data);
            }
        }
        Local_Class local = new Local_Class();
        local.msg();
    }
 
    public static void  main(String[] args){
        Test t = new Test();
        t.display();
    }

}


Output: 
30


Static Nested Class:

A static class that is created inside a class is called Static Nested class.A static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. It can access static data members of outer class including private.

Example:

public class Test{
    private static int var_data = 30;
 
        static class Static_Inner_Class{
            public void msg(){
                System.out.println("private static data "+var_data);
            }
        }
     
    public static void  main(String[] args){
        Test.Static_Inner_Class t = new Test.Static_Inner_Class();
        t.msg();
    }
}

Output:

private static data 30


Example (Using static method): 

public class Test{
    private static int var_data = 30;
 
        static class Static_Inner_Class{
             static void msg(){
                System.out.println("private static data "+var_data);
            }
        }
     
    public static void  main(String[] args){
        Test.Static_Inner_Class.msg();
    }

}

Output:

private static data 30