Sunday 18 September 2011

Multi Threading in Java

What is Thread.?
Process is program in execution.. It contains set of threads.
thread has its own stack and register and share some resources with the another thread. All threads simulates to run concurrently increases the responsiveness of the program. There is a scheduling algorithm which switches the thread .
Used when we want to few things simultaneously like downloading one thing at same time surfing the internet.
How to create thread in Java .?
JVM creates a main thread when program is just started.
Thread is like any normal object that has member, resides on heap.
In java, you can define and instantiate thread by
1. Extending the Thread class
2. implementing the Runnable class
1.  By extending Thread class
You should override the run() of Thread class . Place piece of code that u want to run in separate thread in run() method that you override.
Disadvantage  is that you can extend anything else if you extend Thread class.
class DemoThread extends Thread
{
public void run()
{
//put ur code here that u want to run in separate thread
       // u r free to overload run if u want
}
}
2. implementing Runnable class
class DemoThread implements Runnable
{
public void run()
{
/*put ur code here that u want to run in separate thread*/
       // u r free to overload run if u want
}
}
Instantiating a Thread
Thread class implements Runnable.
You can instantiate as :
Thread t=new Thread(new Runnable(){public void run(){}});
or
Thread t=new Thread(new DemoThread());
Thread constructor takes an argument af any class that implements Runnable interface.
you can also create multiple thread.
Runnable r=new DemoThread();
Thread t1=new Thread(r);// Thread 1
Thread t1=new Thread(r);//Thread 2
Thread t1=new Thread(r);// Thread 3

Starting a Thread
Means to give a thread new stack to run code placed inside run(). This is accomplished by
t.start(). After starting thread doesn’t means that it starts running. It will run when it get chance to execute. That is when start a thread , it moves to runnable state.
State of thread
1. new state---Thread object is created
2. runnable state: when start() is called and new stack is allocated to that thread
3. running—when it gets a chance to run
4. waiting—when blocked because it is unable to run, waiting for resource.
5. Dead---after run() is executed completely . Dead thread cannot be started again.
You cannot start thread again after it is dead. Does this will cause InvalidStateException.
t.start();
t.start();//try this will cause exception
Naming a thread
Constructors of thread:
Thread()
Thread(String s)
Thread(Runnable r)
Thread(Runnable r,String s)
setting a name:
DemoThread t=new DemoThread(“milan”);
or
t.setName(milan);
getting Name of thread
String s=t.getName();
Notes:
Behaviour of thread is not gurranteed . JVM has algorithm  which decided which thread to run.
Multithread is vast topic. So I will continue in next session. 


No comments:

Post a Comment