Describe in detail how deadlocks can be avoided in a system.