Synchronization is basically connected with aquiring the lock,but what is this lock?
Every object in java has its own one and only one lock.So acquiring the lock means,one thread's getting that object's lock letting other threads to wait till it releases it.
Only methods and code blocks can have synchronized option and not variables or classes. 
When a thread goes to sleep,it does not release its locks.
A thread can acquire more than one lock. 
Anyway, synchronization slows down the process as threads have to wait to grab the lock.
Now look at this Q
  • Q)
public class ExceptionEg implements Runnable{
public synchronized void run() {
    System.out.print("A");
    System.out.print("B");
}   
    public static void main(String[] args) {
    ExceptionEg r=new ExceptionEg();
    new Thread(r).start();
    new Thread(r).start();
       
    }
}


 What would be the output?
- We know that a thread can be started only once. Before going to synchronization,you should note that .start() method is called twice.Would that be an issue?
No,because you need to see that it's not the same thread started twice,but two different threads created from the same runnable which is perfectly legal.

-Now from the synchronization aspect,you see that method run() has been synchronized,which means that a thread to execute run() it should first grab the object's lock.

Fine,now how many locks are available? To know that we need to know how many objects are there? You can see there's only one runnable object named 'r' ,start() method is called to the same runnable object 'r' through two different thread objects.So one lock.


First of all note that the aim of these lessons are not to cover simple basics (like no guarantee threads would run in an order) but to give a deeper understanding on tricky points.



Have you ever used a thread in java? You can't say no :D You should've definitely used public static void main(String[] args) { which is a thread!Threads begins as an instance of java.lang.Thread whether run() method is in Thread subclass or a Runnable implemetation ,you anyway need a Thread object.
  • A thread in java always begins by invoking run() method.
  • When you say t.start() the JVM creates a new stack for the newly created thread to run. .You call start() on a Thread instance and not Runnable instance.
  • Thread states are as follows
  
Next PostNewer Posts Previous PostOlder Posts Home