2台のプリンターが同時に印刷できないという問題を2台のプリンターで実装しました。たとえば、プリンター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
正常に動作していますが、代わりにセマフォを変更するにはどうすればよいですか?
編集
問題?
私は 2 台のプリンターを持っていますが、ドキュメント (System.out.println()) を同時に印刷することはできません。そのため、これを行うためにセマフォを使用してプログラムを作成しました。同時に、セマフォを使用する代わりにモニターを使用しようとしています。