Multiple threads in a single process have access to the same memory. By contrast, multiple processes have separate regions of memory and can only communicate by special mechanisms. The processor load s and saves a separate set of registers for each thread.
Remember, each process has one or more threads, and the processor switches between threads.
Mutexes and semaphores:
Each object in Java has its own mutex. Whenever a synchronized method is called, the mutex is locked.
Suppose that thread 1 is executed to just after the first statement. Then, the processor switches to thread 2 and executes both statements. Then, the processor switches back to thread 1 and executes the second statement. In this situation, thread 1 will be waiting for thread 2 to release lock1, and thread 2 will be waiting for thread 1 to release lock2. Both threads will be stuck indefinitely.
we can prevent deadlock if we assign an order to our locks and require that locks always be acquired in order.
For example, if a thread needs to acquire locks 1, 5, and 2, it must acquire lock 1, followed by lock 2, followed by lock 5. That way we prevent one thread trying to acquire lock 1 then lock 2, and another thread trying to acquire lock 2 then lock 1, which could cause deadlock. (Note that this approach is not used very often in practice.)
Hacking a Google interview (From MIT)