Sunday 5 August 2012

Multithreading

What is Multithreading ?
==========================
Multithreading is the ability to do multiple things at once within the same application. It provides finer granularity of concurrency. A thread — sometimes called a lightweight process — is a single sequential flow of control within a program.
Threads are light weight as compared to processes because they take fewer resources then a process. A thread is easy to create and destroy. Threads share the same address space i.e. multiple threads can share the memory variables directly, and therefore may require more complex synchronization logic to avoid deadlocks and starvation.
Every program has at least one thread. Programs without multithreading executes sequentially. That is, after executing one instruction the next instruction in sequence is executed.

Creating threads in Java
==========================
JVM transparently maps Java Threads to their counter-parts in operating system i.e. OS Threads. JVM allows threads in Java to take advantage of hardware and operating system level advancements. It keeps track of threads and schedules them to get CPU time.
There are two approaches to create threads:
Using Interface

1) Create a class where we want to put some code that can run in parallel with some other code and let that class implement the Runnable interface.

class ThreadEx implements Runnable

2) Runnable interface has the run()  method therefore provide the implementation for the run() method and put our code that we want to run in parallel here.

public void run( ){
// write thread behavior code that will be executed by //the thread

3) Instantiate Thread class object by passing Runnable object in constructor
ThreadEx w = new  ThreadEx (“first”);
Thread t = new Thread (w);

4) Start thread by calling start() method
t.start();
Using Inheritance

1) Inherit a class from java.lang.Thread class

         class  ThreadEx  extends Thread

2) Override the run() method in the subclass

          public void run( ){
          // write thread behavior
          // code that will execute by thread


3) Instantiate the object of the subclass

           ThreadEx  w = new  ThreadEx (“first”);

4) Start thread by calling start() method

               t.start();
Thread Priorities
==========================
Threads provide a way to write concurrent programs. But on a single CPU, all the threads do not run simultaneously. JVM assigns threads to the CPU based on thread priorities.
Threads with higher priority are executed in preference to threads with lower priority. A thread’s default priority is same as that of the creating thread i.e. parent thread. A Thread’s priority can be any integer between 1 and 10. We can also use the following predefined constants to assign priorities. For example, we can write the following code to change a thread’s priority.
Thread t = new Thread (RunnableObject); 
// by using predefined constant
t.setPriority (Thread.MAX_PRIORITY); 
// by using integer constant
t.setPriority (7);
The Java runtime environment supports a very simple, deterministic scheduling algorithm called fixed-priority scheduling. This algorithm schedules threads on the basis of their priority relative to other Runnable threads. At any given time, when multiple threads are ready to be executed, the runtime system chooses for execution the Runnable thread that has the highest priority. Only when that thread stops, yields, or becomes Not Runnable will a lower-priority thread start executing. If two threads of the same priority are waiting for the CPU, the scheduler arbitrarily chooses one of them to run. The chosen thread runs until one of the following conditions becomes true: 
  • A higher priority thread becomes Runnable.
  • It yields, or its run() method exits.
  • On systems that support time-slicing, its time allotment has expired.
Then second thread is given a chance to run, and so on, until the interpreter exits.

Some Useful Thread Methods
==========================

sleep(int time) method

  • Causes the currently executing thread to wait for the time (milliseconds) specified.
  • Waiting is efficient equivalent to non-busy. The waiting thread will not occupy the processor.
  • Threads come out of the sleep when the specified time interval expires or when interrupted by some other thread.
  • High priority threads should execute sleep method after some time to give low priority threads a chance to run otherwise starvation may occur.
  • sleep()  method can be used for delay purpose i.e. anyone can call Thread.sleep() method.
  • Note that  sleep() method can throw  InterruptedException. So, you need try-catch block.


yield() method

  • Allows any other threads of same priority to execute (moves itself to end of the priority queue).
  • If all waiting threads have a lower priority, then yielding thread resumes execution on the CPU.
  • Generally used in cooperative scheduling schemes.


Thread states: Life cycle of a thread
=============================



New state
  • When a thread is just created.
Ready state 
  • Thread’s start() method invoked.
  • Thread can now execute.
  • Put it into the Ready Queue of the scheduler.
Running state 

  • Thread is assigned a processor and now is running.
Dead state 
  • Thread has completed or exited.
  • Eventually disposed of by system.
Thread’s joining
=============================
Used when a thread wants to wait for another thread to complete its run( ) method. For example, if thread2 sent the thread2.join() message, it causes the currently executing thread to block efficiently until thread2 finishes its run() method. Calling join method can throw InterruptedException, so we must use try-catch block to handle it.




No comments:

Post a Comment