我已经实现了两台打印机,两台打印机无法同时打印,例如打印机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上打印打印机同时,现在我试图使用信号量来使用显示器。
当您使用良好的旧synchronized
代码块/方法时,monitor
是JVM为您做的事情。看起来像这样:
Object mutex = new Object(); // it can be any object, even a class.
// However, it's preferred to have a separate class only for this.
for (int i = 0 ; i<printers.length; i++) {
printers[i] = new Printer(mutex, pm); // object sharing the mutex object
printers[i].start();
}
和打印机内:
public class Printer extends Thread {
private final Object mutex;
// ..
public Printer (Object mutex, ...) {
this.mutext = mutex;
}
@Override
public void run() {
synchronized(mutex) { //all Printers synchronize the same object
System.out.println("A");
}
}
上面的代码块确保只能在synchronized(mutex)
代码块中只有一台打印机。在您的代码中,即Semaphore mutex = new Semaphore(1);
,即两台打印机不能同时出现。这很简单,简单,不需要共享内存。
另一方面,Semaphore multiplex = new Semaphore(2);
必须是信号量。您可以使用自己的计数器和重新实现Semaphore
。这可能是越来越大的,因为这些问题比看起来更复杂。我建议在必要时使用Semaphore(2)
。
免责声明:我不完全理解问题。反向工程解决方案将导致误解。