信号灯也能被用于保护一个资源的多个复制品或能被多于一个线程同时执行的临界区。
本节的示例代码在 com.elanzone.books.noteeg.chpt3.sect03 package中
在上一节代码的基础上做以下修改:
PrintQueue
private Semaphore semaphore; public static int FreePrinterCount = 3; private boolean freePrinters[]; private Lock lockPrinters; public PrintQueue() { semaphore = new Semaphore(FreePrinterCount); freePrinters = new boolean[FreePrinterCount]; for (int i = 0; i < FreePrinterCount; i++) { freePrinters[i] = true; } lockPrinters = new ReentrantLock(); }
public void printJob(Object document) { try { semaphore.acquire(); int assignedPrinter = getPrinter(); long duration = (long) (Math.random() * 10); System.out.printf("%s: PrintQueue: Printing a Job in Printer %d during %d seconds\n", Thread.currentThread().getName(), assignedPrinter, duration); TimeUnit.SECONDS.sleep(duration); freePrinters[assignedPrinter] = true; } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } }
private int getPrinter() { int ret = -1; try { lockPrinters.lock(); for (int i = 0; i < freePrinters.length; i++) { if (freePrinters[i]) { ret = i; freePrinters[i] = false; break; } } } catch (Exception e) { e.printStackTrace(); } finally { lockPrinters.unlock(); } return ret; }
其他类无变动