Thread and Thread Safety in Java.

 Threads are small programs(piece of code/process) part of large programs/processes. Java allows multiple threads to run concurrently for maximum utilization of CPU.  

Thread creation.
Class A which Either Extend Thread class or implement Runnable interface, both contains run method. We need to override run method. Object of class A becomes a thread. 

Thread life- starts by calling start() method from thread object.
                      this start method internally call run() method ,where we define the code to execute.

E.g.
class MultithreadingDemo (extends Thread)/(implements Runnable) {      public void run() {//code to execute for each thread} }

public class Multithread //driver class
{
    public static void main(String[] args)
    {
            MultithreadingDemo object = new MultithreadingDemo(); //thread created,if we want more thread we make more object
            object.start(); //thread started and will call run method internally
    }
}

Refer-https://www.geeksforgeeks.org/multithreading-in-java/

Thread Safety- It is a process to ensure an object is being worked on by a single thread at a time to avoid inconsistent result by preventing other thread in multithreading. Thread Safety can be attained by following keywords-Synchronized, Volatile, Atomic, Final . 
So when 2 or more threads are trying to run a piece of code concurrently and we have given synchronized modifier. Then a thread will be executed and completed then other will start,i.e. will maintain consistency. Most used one is Synchronized.

Refer-https://www.geeksforgeeks.org/thread-safety-and-how-to-achieve-it-in-java/


Comments

Popular posts from this blog

Polymorphism

Static Keyword in Java