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.
) {
}
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
Post a Comment