In very simple way When two processes are waiting for each other for infinite time It is called deadlock
I think, this problem can be solved by, at first thread1 check status of Y, if Y is locked by another thread (thread2), loop the process: wait for a random interval of time and don't hold lock on X. Check status of X, Y, if both of X and Y are not locked then run thread1.
Deadlock is a famous problem you can avoid simply by careful programming. let us assume that we have two threads, thread 1, and thread 2. Let us assume, as well, that we have two objects, object x, and object y. If thread 1 holds a lock on object x and waits for a lock on object y, and thread 2 holds a lock on object y, and waits for a lock on object x then threads will be waiting forever! and this is what we call a deadlock situation.