Object o1 = new Object();
Object o2 = new Object();
Thread1:
synchronized(o1){
Thread.sleep(1000);
synchronized(o2){
//do something
}
}
Thread2:
synchronized(o2){
Thread.sleep(1000);
synchronized(o1){
//do something
}
}
Test code:
new Thread1().start();
new Thread2().start();
does above code always deadlock, if not, why?
Yes, because once a thread wakes up, it will not be able to enter the next synchronized section because the lock is already taken.
(There could be a theoretical scenario where there will not be a deadlock - if one thread gets both locks before second thread got cpu time to even get the first lock)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With