我已经用两台打印机实现了一个问题,两台打印机不能同时打印,例如打印机 A 正在打印而 B 不能,就像它一样简单,我这样做Semaphores
如下:
我的Printer.class
样子
public class Printer extends Thread {
Semaphore mutex,multiplex;
PrinterMachine printerMachine;
String printer = "";
public Printer(Semaphore mutex, Semaphore multiplex, PrinterMachine pm) {
this.multiplex = multiplex;
this.mutex = mutex;
printerMachine = pm;
}
@Override
public void run() {
String printer = "";
for(;;) {
try {multiplex.acquire();} catch (InterruptedException e) {}
try {mutex.acquire();} catch (InterruptedException e) {}
if(printerMachine.getCanPrintA()) {
printer = "A";
printerMachine.setCanPrintA(false);
}
else {
printer="B";
printerMachine.setCanPrintB(false);
}
mutex.release();
try {Thread.sleep(100);} catch (InterruptedException e) {}
System.out.println(printer);
if(printer.equals("A")) {
printerMachine.setCanPrintA(true);
}
else {
printerMachine.setCanPrintB(true);
}
try {Thread.sleep(100);} catch (InterruptedException e) {}
multiplex.release();
}
}
}
然后我有一个共享变量的类
class PrinterMachine{
public volatile Boolean canPrintA = true,canPrintB = true;
.... //Getter and Setter
然后我有我的主要
public static void main(String[] args) {
Semaphore mutex = /* COMPLETE */ new Semaphore(1);
Semaphore multiplex = /* COMPLETE */ new Semaphore(2);
PrinterMachine pm = new PrinterMachine();
Printer printers[] = new Printer[10];
for (int i = 0 ; i<printers.length; i++) {
printers[i] = new Printer(mutex,multiplex,pm);
printers[i].start();
}
try {
Thread.sleep(5000);
}
catch(InterruptedException ie) {}
for (int i = 0 ; i<printers.length; i++) {
printers[i].stop();
}
}
它工作正常,但我想知道如何更改我的信号量以monitors
代替使用?
编辑
问题?
我有两台打印机,我不能同时打印一个文档(System.out.println()),所以我用信号量做了一个程序来做到这一点,这样我就不能在 A 和 B 打印机上打印同时,现在我正在尝试使用监视器而不是使用信号量来完成它。