Saturday, December 19, 2009

Multithreading

What is multithreading:

Java support multithreading programing. A (multithreaded) program contains two or more parts that can run concurrently. Each part of such program is called a "Thread" and each thread defines seperate path of exectution.

Every thread has own independent “call stack”.
Multitasking – 1) process based multitasking, 2) thread based multitasking.
1) Process is a program in running state. In process based multitasking, which allows processes (i.e. programs) to run concurrently.
2) A thread is a part of program. In thread-based multitasking, multiple threads in a program run concurrently.

Advantages of thread-based multitasking over process-based multitasking are
1) At runtime, Threads in a program shares same memory space.
2) Context switching between thread is less expensive.
3) Cost of communication between threads is relatively low.
4) Multithreading can make your program more responsive, interactive and run faster than non-threaded version.


What is Main Thread:
The main thread is created automatically when your program is started, it can controlled through a Thread object. You can obtain the reference of it by calling the method currentThread() which is a public static member of Thread.

Case #1
package threads;
public class MainThread {
public static void main(String[] args) {
Thread t = Thread.currentThread();
System.out.println("Main Thread: "+t);
}
}

Case #2
package threads;
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet{
public void paint(Graphics g) {
Thread t = Thread.currentThread();
g.drawString("Main Thread: "+t,0, 100);
}
}


Creating Threads:

The thread is an independent sequential path of execution within a program. At runtime, threads in a program shares common memory space so they share both data and code (i.e. they are lightweight compared to process).
A thread in Java is represented by an object of the java.lang.Thread class. Implementing thread is achieved in two ways-
implementing the java.lang.Runnable interface.
extending the java.lang.Thread class

The Thread class implement the Runnable interface and the Runnable interface has only one method that is public void run().

At minimum you have to know following methods of Thread class:
public void run()
public void start()
public static void sleep()
public static void currentThread()
public static void yield()
public void join()
public boolean isAlive()
public String getName()
public void setPriority()

Constructors of the Thread class:
Thread()
Thread(String name)
Thread(Runnable r)
Thread(Runnable r, String name)

Implementing the Runnable interface:
To implement Runnable interface, a class need to implement a single method called run().
public void run(){
// code
}
Steps:
1) A class implement the Runnable interface, providing the run() method that will be executed by the thread.
2) An object of Thread class is created by passing a Runnable object as argument to thread constructor.

3) The start() method is invoked on Thread object created in previous step.


package threads;

public class Test {
public static void main(String[] args) {
ThreadRunnable r = new ThreadRunnable();
Thread t1=new Thread(r);
t1.start();
try {
for(int i=0;i<5;i++){ i="0;i<5;i++){">


Extending the Thread class:
Steps:
1) A class extending the Thread class overrides the run() method from the Thread class.
2) This subclass may call may call a Thread constructor explicitly in its constructor to initialize the thread using super().
3) The start() method inherited form the Thread class is invoked on the object of the class to make the thread eligible for running.

package threads;

public class Test {
public static void main(String[] args) {
Thread1 t1=new Thread1();
t1.start();
try {
for(int i=0;i<5;i++){ i="0;i<5;i++){">

When creating threads, implementing the Runnable interface is good programming practice because you can extend other class as well as implementing the Runnable interface.


Synchronization:
When two or more threads need access to shared resource, they need some way to ensure tha the resource will be used by only one thread a time. The process by which this is achieved is called Synchronization. Each resource in java has its own lock. So threads first obtain the lock then use that resource.
You can synchronize your code in either of two ways -
Synchronized Methods:
To enter the object’s lock, you, just call a method that has been modified with synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on same object have to wait. A thread relinquishes the lock simply by returning from synchronized method, allowing the next thread waiting for this lock to proceed.

Synchronized blocks:
Imagine that you want to synchronize access to objects of the class that was not designed for multithreaded access. That is this class does not use synchronized methods. This class was not created by you but by the third party and you have not right to change the code of that class.
Solution of this problem is very simple: You simply put calls to the methods defined by this class inside a synchronized block.
Synchronized(objectRef){
ObjectRef.method1();
// statements
}

Interthread Communication:

In Java, threads communicate using three methods – wait(), notify(), and notifyAll(). These methods are implemented in Object class, so all classes have these methods. All three methods can be called only from within a synchronized context.
wait() tells the calling thread to give up the lock and go to sleep until some other thread enters the same lock and calls notify().
notify() wakes up a thread that is waiting(by called wait) for the same object.
notifyAll() wake up all the threads that called wait() on the same object. One of the threads will be granted the access.
Methods in Object class:
final void wait() throws InterruptedException
final void notify()
final void notifyAll()


package threads;
public class PC {
public static void main(String[] args) {
Q q=new Q();
new Thread(new Consumer(q)).start();
new Thread(new Producer(q)).start();
}
}
class Q{
int n;
boolean valueSet=false;
synchronized int get(){
while(!valueSet)
try{
System.out.println("before wait in GET");
wait();
}catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: "+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n){
while(valueSet)
try{
System.out.println("before wait in PUT");
wait();
}catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n=n;
valueSet=true;
System.out.println("Put: "+n);
notify();
}
}
class Producer implements Runnable{
Q q;
Producer(Q q){
this.q=q;
}
public void run() {
int i=0;
while(i<100){ // condition for stooping the loop after 100;
q.put(i++);
}
}
}
class Consumer implements Runnable{
Q q;
Consumer(Q q){
this.q=q;
}
public void run() {
int k=0;
while(k<100){ //condition is only to stop the loop there no other use of k
q.get();
k++;
}
}
}


What is multithreading:
Java support multithreading programing. A (multithreaded) program contains two or more parts that can run concurrently. Each part of such program is called a "Thread" and each thread defines seperate path of exectution

No comments:

Post a Comment