Deadlock is caused when two threads try to obtain the same, multiple locks in different order:
synchronized (A) {
synchronized (B) {
}
}
synchronized (B) {
synchronized (A) {
}
}
The only way to prevent deadlocks is to make sure that all threads get locks in the same order - either they all do A, then B, or they all do B, then A.
, . , , .