Suppose I have threads t1,t2,t3……t10 and I need to access the printer and scanner, order is first scan and then print using this threads so how do I ensure that t1,t2…t10(by multiple users) can access the scanner or printer without deadlock.
t1 finishes his job of scanning and waiting for printer and now t2 is doing job of printing the doc. So how do I ensure that t1 should not interrupt the job t2. now t2 finishes his job of printing same user wants to scan the another document but it is not released by t1. so deadlock between t1 and t2, t1 wants printer and t2 wants scanner but they already holding the other ones resource.
A good way to implement such a mechanism is to use a queue, for example a thread safe BlockingQueue and have 2 consumer threads:
Then your T0…T10 simply put jobs in one of the queues and wait (or not) for them to be executed when the Printer/Scanner is ready.
By doing that you remove the need to lock on the client/producer side and let the consumer side (Printer and Scanner) to manage their jobs.