Wednesday, December 12, 2012

Multithreading in Java !!!!!


A multiprocessor system can actually do more than one thing at at time but with Java threads, it can appear that you are doing several things simultaneously. Execution can move back and forth between stacks so rapidly that you feel as though all stacks are executing at the same time. 

Thread t = new Thread(r);

Thread is a class in the java.lang package. And this package is imported by default even without package declaration.    A Thread object represents a thread of execution, you will create an instance of class Thread each time you want to start up a new thread of execution.


Three states of new thread


  • When thread is new !

A thread instance has been created but not started. In other words, there is a Thread object but no threa of execution.


  • When thread is in Runnable state !  (t.start();)

When you start the thread, it moves into the runnable state. This means the thread is ready to run and just waiting for its chance to be selected for execution. 


  • When thread is in Running state !
Only the JVM thread scheduler can make that decision. You can sometimes influence that decision but you can not force a thread to move from runnable to running. 


The thread scheduler can move a running thread into blocked state for a variety of reasons. The scheduler will move the thread out of the running state until something becomes available. It can put the thread in sleep by sleep(). You can force the currently running thread to leave the running state and give chance to another  thread to run. In the sleep() method, that's for sure that sleeping thread will not become the currently running thread before the length of sleeping time has expired. 

And how will you apply the sleep() method, that also simple, just write down Thread.sleep(1000); This mean the current thread will not be execute till 1 second. Everything we write down in this method is in milliseconds. 

When you pass a Runnable to a Thread constructor, you are really just giving the Thread a way to get to a run() method. You are giving the Thread its job to do.


___________________________________________

Here I am giving the example of Thread which is taken from Head First Java book for your reference : 

In this example we took two thread and give there name and also set small scenario like what happen if one of the thread sleep or wake up that is runnable and what happen if there is not enough money for them in bank account.



class BankAccount{

private int balance = 100;

public int getBAalance(){
return balance;
}
public void Withdraw (int amount){
balance = balance - amount;
}
}



public class RyanAndMonicaJob implements Runnable {

private BankAccount account = new BankAccount();

public static void main(String[] args) {


RyanAndMonicaJob theJob = new RyanAndMonicaJob();
Thread one = new Thread(theJob);
Thread two = new Thread(theJob);

one.setName("Ryan");
two.setName("Monica");
one.start();
two.start();

}

public void run(){
for(int x = 0; x<10;x++){
makeWithdrawl(10);
if(account.getBAalance() < 0){
System.out.println("Overdrawn!");
}
}
}

private void makeWithdrawl(int amount){

if(account.getBAalance() >=amount){
System.out.println(Thread.currentThread().getName()+" is about to withdrawl.");
try{
System.out.println(Thread.currentThread().getName()+ " is going to sleep.");
Thread.sleep(500);
}catch (InterruptedException ex){ex.printStackTrace();}
System.out.println(Thread.currentThread().getName()+" woke up.");
account.Withdraw(amount);
System.out.println(Thread.currentThread().getName()+" completes the withdrawl.");
}
else{
System.out.println("Sorry,not enough for " + Thread.currentThread().getName());
}
}
}


_____________________________________________

Output:


Ryan is about to withdrawl.
Monica is about to withdrawl.
Ryan is going to sleep.
Monica is going to sleep.
Ryan woke up.
Monica woke up.
Ryan completes the withdrawl.
Monica completes the withdrawl.
Ryan is about to withdrawl.
Monica is about to withdrawl.
Ryan is going to sleep.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Ryan woke up.
Ryan completes the withdrawl.
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!

_____________________________________________

Monday, December 10, 2012

Understand Wrapper and parse !!!


Practically Wrapper mean wrap the primitive in different value, so that we can use it as per the situation. 

There is wrapper class for every primitive in java. The wrapper class for int is Int, float is Float, char is Character, byte is Byte, double is Double and so on.


                Integer int1 = new Integer("4");
Integer int2 = new Integer("1");
Double int3 = new Double(123.12);

i = int2 + int1;
System.out.println(i);        //5


When we convert the value of wrapped numeric to a primitive than we use following value() methods. That mean we put byteValue(), doubleValue() and so on. 

byte b = int1.byteValue();
System.out.println(b);           

short s = int3.shortValue();
System.out.println(s);

double d = int2.doubleValue();
System.out.println(d);


Following example show the created value of int4 is 5, cause when you convert binary of 101 than you will get 5. So int = 5 now. This is called valueOf() method.

Integer int4 = Integer.valueOf("101",2);
System.out.println(int4);  


Now we look on some parseXxx()  method, it is nearly like valueOf() method.
Following example is for converting string to other primitive what ever you like to apply.


               double d1 = Double.parseDouble("789.456");
System.out.println(d1);


               long l1 = Long.parseLong("101",2);
System.out.println(l1);

Now above example is same like we apply in valueOf() methos, we get same output but using different method.

        

Now when we use toXxxString() method than it convert the following:



                String s1 = Integer.toHexString(123);  
System.out.println(s1);                             // 7b

String s2 = Long.toOctalString(123);
System.out.println(s2);                              //173

String s3 = Double.toHexString(789);
System.out.println(s3);                             //0x1.8a8p9




Now toString(), in this method you can convert every primitive values to string:


               Long l = new Long("789456123");
System.out.println(l.toString());        //789456123

String l2 = Long.toString(789456123);


You can take different primitive value.





Tuesday, December 4, 2012

Understand Abstract class and Interface !!!


Abstract class and Methods



- An Abstract class can not be instantiated but they can be subclassed.

- An Abstract method is method that is declared without an implementation without braces and followed by semicolon.

Example:

public abstract class Animal{

        abstract void eat();

}

- All abstract methods must be implemented in the first concrete subclass    in the inheritance tree. 

- An abstract class can have both abstract and non abstract methods.

- When you don't want a class to be instantiated mark the class with abstract keyword.

- If a class has even one abstract method, the class must be marked abstract.


We have here AnimalObject in above image, might be all three sublcass that is Lion, cat and zebra behave totally different but other thing we find common is eat and roam. You can take advantage of similarities and declare all the animals to inherit from the same abstract object. Lion , Cat and Zebra inherit from Animal.

Example:

public abstract class Animal{
         
         abstract void eat();
         abstract void roam();
}


class Lion extends Animal{

        void eat();{
       void roam();{

}

class Cat extends Animal{

        void eat();{
       void roam();{

}


class Zebra extends Animal{

        void eat();{
       void roam();{

}


Now all this above three non abstract subclass of Animal that is Lion, Cat and Zebra must provide implementation.



Interface 



- An interface is a reference type similar to a class that can certain only constants method signature and nested types. There are no method bodies. 

- Use interface when you want different behavior different classes.

- Interface can not be implemented by class or extended by other interfaces.

- Create an interface using the "interface" keyword instead of class.


Example:

public interface mainInterface extend Interface1, Interface2, Interface3{

               void doSomething (int a, float y);
               int doSomethingElse(String s);


The public access specifier indicates that the interface that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.

An interface can extend other interfaces just as a class can extend or subclass another class. As you know that the class can only extend other class but interface can extend any number of interfaces. And it declare by  comma as shown in above example. 



Thank you for your time..............