Multi-threading

The main purpose of multithreading is to provide simultaneous execution of two more parts of a program to maximum utilize the CPU time.

Threads are the lightweight sub-process , they share the common memory space.

 

Life cycle of thread:

java threads

Thread Priorities

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

Common Thread methods:

getName()
getPriority()
isAlive()
join()
run()
sleep()
start()
setPriority()
setName()

There are 2 ways of creating a Thread.

1. Extends Thread class
2. Implement Runnable interface

Example:

class Multi extends Thread {
@Override
public void run(){
System.out.println(“Thread is running”);
}

public static void main(String args[]){
Multi t1 = new Multi();
t1.start();
}

Note: t1.start() will start a thread and call the run() method. We normally do processing of threads inside the run() method.

public void run(){

    // thread inside the run   method  will sleep for 500 milliseconds
    for(int I = 1; I < 5; i++){ try{ Thread.sleep(500); 

    } catch(InterruptedException e){ //To Do }

    System.out.println(i);

    System.out.println(Thread.getName());

   }

}

Implement Runnable interface:

class MultiR implements Runnable{

      public void run(){

           System.out.println(“Thread is running”);

       }

       public static void main(String args[]){

                 MultiR mr = new MultiR();

                Thread t1 = new Thread(mr);

                 t1.start();

      }

Inter-thread communication:

Java threads can communicate with each other with the help of methods like wait(), notify() and notifyAll().

wait() -> It informs to the calling thread to give up the monitor space and go to sleep.
notify() -> It informs the first thread to wakeup who went to sleep due to wait() method call.
notifyAll() -> It will send request to all threads to wake up.