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
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.
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 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.