lookiplace.blogg.se

Lock queue
Lock queue













PrinterQueue printerQueue = new PrinterQueue() ("%s: The document has been printed\n", Thread.currentThread().getName()) (Thread.currentThread().getName() + ": PrintQueue: Printing a Job during " + (duration / 1000) + " seconds :: Time - " + new Date()) Long duration = (long) (Math.random() * 10000) Private final Lock queueLock = new ReentrantLock() A lock is maintained by printer to start new print job as soon as current print job is finished. This class represent the printer queue/ printer. ("%s: Going to print a document\n", Thread.currentThread().getName()) Public PrintingJob(PrinterQueue printerQueue) This class implements Runnable interface, so that printer can execute it when it’s turn come. This class represents an independent printing which could be submitted to printer. Once printer is done with print job in hand, it will pick another job from queue and start printing. Rest of jobs will wait there for their turn. Printer will take a job from printer queue and print it. You can submit a number of print jobs to printer during varying time interval or simultaneously. In this example, program will simulate the behavior of a printer. Finally unlock() is called, and the Lock is now unlocked so other threads can lock it. Any other thread calling lock() will be blocked until the thread that locked the lock calls unlock(). Here is the simple use of Lock interface.įirst a Lock is created. ReentrantLock is one such implementation of Lock interface. Since Lock is an interface, you need to use one of its implementations to use a Lock in your applications. A Lock is, however, more flexible and more sophisticated than a synchronized block. Lock InterfaceĪ .Lock is a thread synchronization mechanism just like synchronized blocks. In this tutorial, we will see a basic usage of Lock interface to solve printer queue problem.

#LOCK QUEUE CODE#

Java provides another mechanism for the synchronization of blocks of code based on the Lock interface and classes that implement it (such as ReentrantLock).

lock queue

We are already aware of basic concepts around thread synchronization and various mechanisms using synchronized keyword.













Lock queue