Threads

thread
θrɛd/
noun
  1. 1.
    a long, thin strand of cotton, nylon, or other fibres used in sewing or weaving.
    "he had a loose thread on his shirt"
  2. 2.
    a theme or characteristic running throughout a situation or piece of writing.
    "a major thread running through the book is the primacy of form over substance"
    synonyms:train of thought, driftdirectionsensethemesubject mattermotif,tenorstrainthrustsubjectgistburdenactionMore

The general meaning of the term "Thread" is given above. In Computing Thread is a sequence of operations or instructions which runs independently from the other instructions in a particular program.

when we write a program in Java, first the compiler execute the instructions given in the main method  as in the given order. if call for a method it will goes to the method stack and execute the instructions in the given method




class A{
     public static void main(String args[]){
             System.out.println("main method");
             int i=10;
             method1();
             System.out.println("end of main method");      
     }
     static void method1(){
            System.out.println("first method");
            method2();
            System.out.println("end of first method");
    }
     static void method2(){
            System.out.println("second method");
            method3();
            System.out.println("end of second method");
    }
     void method3(){
            System.out.println("third method");
            System.out.println("end of thirdmethod");
    }
}

Output:
main method
first method
second method
third method
end of third method
end of second method
end of first method
end of main

Below is the snapshot of call stack when executing the third method.


the above program run in a one thread where all the instruction execute sequentially. But there are applications which need some processes to run concurrently.

concurrency is a concept or idea of executing several computations at once. but this is not possible with a one processor which can execute one instruction at a time.

The Multi Tasking machines which was introduce later was able to  achieved this by scheduling the processes which will give the user a feeling as they running simultaneously but in the core they are running one after the other.  Multi tasking can be done in two ways,

  • Process base multi tasking (Multi Processing)
  • Thread base multi tasking (Multi Threading)
A Process has at-least a one thread which is the main thread and there can be several threads in a one process.

Thread is a light weight sub process which share resources allocated for the process and threads are independent from each other.

There are two ways to make threads in Java
  • Extending Thread Class
  • Implementing Runnable Interface

class ExtendedThread extends Thread{
    public void run(){
           System.out.println("Thread Run Method");
    }

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

class RunnableClass implements Runnable{
    public void run(){
           System.out.println("Thread Run Method");
    }

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

There are 5 statuses in the life cycle of a thread.

  • New - Thread is created (Thread t = new Thread(ob))
  • Runnable - call for start method (t.start())
    • Ready - ready to be executed but not executing
    • Running - selected to run by thread scheduler 
  • Timed Waiting - waiting for a specific time provided by code (t.sleep(2000))
  • Waiting - waiting without a timeout period (until some other thread finish executing)
  • Blocked - has been locked by a synchronized method or block
Thread scheduler  select which thread to be run according to their priority and other facts. mainly it use time slicing technique which slice the time into equal size of portions and threads will run only for that period of time. even if the thread is not finished executing other thread will get a chance after the time period. since this is happening really fast users will feel it like all the threads are executing concurrently. Another method used by the thread scheduler is preemptive which will let a thread run until an interrupt occurs or until higher priority thread come across.

Synchronized methods or blocks belongs to a shared instance  can be used only by one thread at a time which means it will get locked when a thread running that particular method or block labeled as synchronized and it will be released after executing that method or block.
//method
synchronized void synchronizedMethod(){
     
}

//block
void synchronizedBlock(){
     synchronized(this){
     }    
}


synchronization also can be used in static methods and blocks which will lock that method or block to other threads and release when its done executing.

//method sample
synchronized static void staticSynchronizedMethod(){

}

//block sample
class A{
   static void staticSynchronizedBlock(){
       synchronized(A.class){
       }
   }
}


References:
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
http://www.javatpoint.com/multithreading-in-java
http://tutorials.jenkov.com/java-concurrency/synchronized.html


Comments

Post a Comment

Popular posts from this blog

Flow Charts

ධර්මය, ආක්‍රමණය හා යුද්ධය

ආගමක් නැති මනුස්සයෙක්