Wednesday, January 7, 2015

multi-threading

Multithreading


Thread, thread refers to the smallest part of the program. If two or more parts of the program run concurrently then this is called multithreading. Each thread defines a separate path of execution. One thread can pause without stopping other parts of program. In java “Thread” is a predefined class which is used to create single or multiple thread and it is store in Java.Lang package.

OS supports two types of tasking-

1)    Process-based multitasking
2)    Thread-based multitasking

When more than one program run concurrently then this concept is called Process-based multitasking. For example- web browser and music running concurrently.

When one program perform more than one task then this concept is called thread-based multitasking. For example- formatting and printing at the same time on a text editor.

Some Methods of thread class.

1)    currentThread() : used to get the reference of current running thread. It is a static method.
2)    setName( String name-of-thread) : used to set the name of thread. It is a final method.
3)    getName(): used to get the name of thread. It is a final method.
4)    setPriority(int level) : used to set the priority of thread. It is a final method.
5)    getPriority() : used to get the priority of thread. It is a final method.
6)    join() : wait for a thread to terminate or wait until a specified thread join in.
7)    run() : starting entry point of the thread.
8)    start() : used to implicitly invoke the run method (start a thread by calling its run method).
9)    sleep(int miliseconds) : used to stop the execution of current thread specified by the parameter supplied to it. It is a static method.

Main  thread :  When a java program starts up, one thread starts running immediately called main thread. It executes when program begin execution.
            It is the thread from which other child threads will be spawned. Often it must be the last thread to finish execution because it performs various shutdown actions.  Main thread is created automatically when program is started.

Thread priority decides, when to switch from one thread to another thread.

1)    A thread can willingly relinquish control: this can be done by sleeping, blocking or pending i/o.
2)    A thread can be pre-empted by a higher priority thread.
In java every thread belongs to a group and by default they all belong to main group. Group of thread is a data structure that handles collection of threads. Java always assign priority of each thread and priority is an integer no. between 1to10. This priority is used by CPU to decide when to switch from one running thread to another. This concept is context switch. This is pre-emption technique.

States of thread – there are 6 states
1)    Running - as soon as CPU start execution of its body.
2)    Ready to run – as soon as thread gets CPU.
3)    Suspend – when execution is suspended by sleep method.
4)    Block State – when resources requires by thread are not available.
5)    Terminate – execution completed.
6)    Resume – after suspend, thread can resume.


Once a thread gets terminate then it can’t be resume. If OS is pre-emptive type then higher priority threads gets more CPU time than lower priority thread. By default priority of thread is always 5. Priority is set using setPriority() method. Priority is also used to determine how one thread should be treated with respect to other thread.

Wednesday, October 8, 2014

Interface

Interface


Interface is a collection of methods and variables. Let’s see its general syntax:

Access_specifier interface interface_name
{
Datatype variable_name = value; \\ can declare multiple variables.
Returntype method_name1 (list of parameters);
Returntype method_nameN (list of parameters); \\ can declare multiple methods.
}

Points to remember about Interface:

1.     Interface is used to achieve runtime polymorphism and multiple inheritance.
2.     By default, methods and variables are public. All methods should be declared as public.
3.     Methods of interface never contain the body-part.
4.     Variables of interface should be initialized in the interface.
5.     It doesn’t contain constructors, object initialization blocks and static initialization blocks.
6.     By default methods of interface are abstract methods, and variables are final and static.
7.     ‘Implements’ keyword is used to implement methods of interface.
8.     If any class implements the interface and doesn’t fulfil the body-part of all its methods then, it is necessary to declare that class as abstract class. One interface can’t implement another interface.
9.     One interface can extends another interface. And one class can implement more than one interfaces.

Example:   inter.java

interface person
{
      string getadd();
      string getname();
      int age();
}
abstract class inter implements person {
      int age() {
      // definition of method
}
string getname() {
      // definition of method
}
}

This class must be declared as abstract because it doesn’t contain all the methods of interface person. If you don’t want to declare the class as an abstract class then, whether you require all methods or not you should define all the methods of the interface.

Example of inheritance of interfaces:

interface A {
      Void fun ();
}
interface B extends A {
      Void fun1 ();
}
class C implements B,A
{
      public void fun() {
      // body-part, if require
}
public void fun1() {
      // body-part, if require
}
}

Here , one class c has implemented 2 interfaces. 
One more thing , a class can extends another class and implements interfaces at the same time. Like this:

class apple extends fruits implements sweetfruits
{
      // body-part
      // it requires to define methods of sweetfruits interface.
}





Tuesday, September 30, 2014

Abstract Cass

Abstract Class


Abstract classes are used to achieve abstraction. Any class which contains an abstract method should be declared as abstract. We can’t create object of an abstract class. Abstract class can also contain concrete methods so that’s why it doesn’t provide 100% abstraction.

Syntax:           abstract class class-name {  }

abstract is a keyword which is used to achieve abstraction.

Abstract class doesn’t contain the definition of abstract method. It only contains the declaration of the abstract method. Abstract methods are defined to achieve runtime polymorphism. An abstract method can’t be a private, static and final method. Abstract class can contain more than one abstract functions but subclass should contain the definition of all the abstract methods.  Example:          
                               
abstract class A
{
      abstract void absfun(); // abstract method ends with semicolon.
      public void concfun()
      {
            System.out.println("concrete method");
      }
}
class C extends A
{
      void absfun()
      {
            // definition of abstract method in derived class.
            System.out.println("abstract method");
      }
      public static void main(String args[])
      {
            C ob= new C();
            ob.absfun();
            ob.concfun();
      }
}
Output: abstract method
        Concrete method

If any class is derived from an abstract class then it is subclass’s responsibility to fulfil the body part of abstract method of superclass. And if any derived class doesn’t fulfil the body part of abstract method of super class then it is necessary to declare the derived class as abstract class. One abstract class can also inherit or extends another abstract class.  

Abstract class can also contain constructors, member variables. Abstract class is different from interface. Object of abstract class can’t be created. Abstract class must contain ab abstract method. Abstract methods are used where two or more subclasses are expected to do similar things in different ways through different implementation. Let’s see an example:  

abstract class figure
{
public int dim1=10, dim2=20;
abstract int area (); // abstract method ends with semicolon.
}
class rectangle extends figure
{
int area()
{
return(dim1*dim2);
}
}
class triangle extends figure
{
int area()
{
return((dim1*dim2)/2);
}
}
class abstractcls
{
public static void main(String args[])
{
//figure ob= new figure();  illegal, coz we can’t create instance of abstract class
figure ob= new rectangle(); // or rectangle ob= new rectangle();
triangle ob1= new triangle();
System.out.println("area of rect = "+ ob.area()+"\n area of tri = "+ ob1.area());
}
}
Output: area of rect = 200
        area of tri = 100

Abstract methods are used where two or more subclasses are expected to do similar things in different ways through different implementation. Abstraction is used to hide the complexity.


Thursday, September 25, 2014

Static Import Statement

Static Import Statement

As you know that import statement import the standard as well as user defined packages in java source file. In this topic we will discuss why import the packages statically i.e. by using static import.

So in the answer I would say, by using static import, we can access static data types and static methods directly in to class. Let’s take an example. But before that we should know the syntax.

Syntax:   import static packagename1 [ . packagename2 [ . packagenameN ]].  classname.(static field/static method/*) ;

Example:  import static java.lang.system.*;
                   import static java.lang.system.out;

java language has many standard packages. One of them is lang . lang package contain many classes like Syatem, Math. These classes contain static methods and fields which we can use directly. Let’s understand this static import statement with Math class.

Math class
Class java.lang.Math {
            public static double pow (double a , double b){
            // body part of pow method
}
public static double sqrt (double a){
            // body part of sqrt method
}
// rest of the methods
}

Math class would probably has this type of body. So if we do not import this Math class and System class with Static then to use pow()  sqrt() and println() methods, statement should be like this-

System.out.println(Math.sqrt( Math.pow(3,2)));  // square root of 3 * 3. output is 3

Now if we’ll import the classes System and Math with static as

import static java.lang.System.out;
import static java.lang.Math.*;

then  we can write the highlighted statement as

out.println(sqrt(pow(3,2)));    // output is 3


so if you import the classes static then you can use the static data types and static methods directly in to your java file.

Tuesday, September 23, 2014

Data member access table


You often get confused with the accessibility of data-members and methods in different classes , packages etc. So here is a table to help – class member access table. This table will help you to know , which type of class members(like- public , private, protected, default) are accessible in different conditions (like-  with-in same or different package/class and subclass or non subclass )


Condition

private
default
protected
public
With-in same class

 Y       
 Y
 Y
 Y
Same package and non-subclass
No
 Y
 Y
 Y
Same package and subclass
No              
 Y    
 Y
 Y
Different package and subclass
No
No
 Y
 Y
Different package and non-subclass
No
No
No
 Y

Y stands for 'yes'. 

All the four data members can be accessed anywhere with-in the same class.

If a single package contains different classes which are non-subclasses then private member of one class can’t be accessed in other class.

If a single package contains different classes and some of them are subclasses then private member of super class can’t be accessed in its subclasses classes/ derived classes.

If we have two or more packages and there is some inter-relation (inheritance) in between the classes of these packages then only protected and public data-member and methods are accessible.  

If we have two or more packages then only private members of classes can be accessed by the other classes of other packages.