Why is Locking of a Method or Block of Code for Thread Safety is called “Synchronized” and not “Lock” or “Locked

When a method or block of code is locked with the reserved “synchronized” key word in Java, the memory (i.e. heap) where the shared data is kept is synchronized. This means,When a synchronized block or method is entered after the lock has been acquired by a thread, it first reads any changes to the locked object … Read more

What is the Difference Between Yield and Sleeping? What is the Difference Between the Methods sleep( ) and wait( )

When a task invokes yield( ), it changes from running state to runnable state. When a task invokes sleep ( ), it changes from running state to waiting/sleeping state. The method wait(1000), causes the current thread to sleep up to one second. A thread could sleep less than 1 second if it receives the notify( … Read more

Briefly Explain High-Level Thread States

The state chart diagram below describes the thread states.   Runnable: A thread becomes runnable when you call the start( ), but does  not necessarily start running immediately.  It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities. MyThread aThread = new MyThread(); aThread.start();                   //becomes runnable Running: … Read more

Which one would you prefer and why

The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice. Also note how the threads are started in each of … Read more

Explain Different Ways of Creating a Thread

Threads can be used by either: Extending the Thread class. Implementing the Runnable interface. Using the Executor framework (this creates a thread pool)   By extends: class Counter extends Thread {   //method where the thread execution will start public void run(){ //logic to execute in a thread }   //let’s see how to start the threads public static void main(String[] … Read more