以下是我的程序。一直是线程0获得打印机,其他线程没有获得它。有一个打印机对象,我希望多个作业线程使用打印机。如何使这个程序工作,让所有工作都能获得打印机。对我来说,代码流似乎是正常的。我正在同步单个打印机对象。请帮忙。
package classesTesting;
public class PrinterQueue {
final static Printer printer = new Printer();;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("In Main");
for (int i = 0; i < 5; i++) {
new Thread(new Jobs(), "Thread - " + i).start();
System.out.println("started " + i + " thread");
}
}
}
class Printer {
private boolean isUsed;
Printer() {
this.isUsed = false;
}
public void setUsed(boolean used) {
this.isUsed = used;
}
public boolean isUsed() {
return this.isUsed;
}
}
class Jobs implements Runnable {
String name;
boolean isDataAvailble;
Jobs() {
this.isDataAvailble = true;
}
public void setNoData(boolean noData) {
this.isDataAvailble = false;
}
@Override
public void run() {
while (isDataAvailble) {
if (PrinterQueue.printer.isUsed()) {
try {
System.out.println(Thread.currentThread()
+ "WAITING FOR PRINTER");
synchronized (PrinterQueue.printer) {
PrinterQueue.printer.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
synchronized (PrinterQueue.printer) {
System.out.println(Thread.currentThread() + "GOT PRINTER");
PrinterQueue.printer.setUsed(true);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrinterQueue.printer.setUsed(false);
PrinterQueue.printer.notify();
}
}
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
你好,我已经修改了我的程序,先获取锁再进行条件检查。即使如此,线程0仍然始终获得打印机。其他线程会挨饿。
修改后的程序:
package classesTesting;
public class PrinterQueue {
static Printer printer;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("In Main");
printer = new Printer();
for (int i = 0; i < 5; i++) {
Jobs j1 = new Jobs();
j1.setPrinter(printer);
Thread t1 = new Thread(j1, "Thread - " + i);
t1.start();
System.out.println("started " + i + " thread");
}
}
}
class Printer {
private boolean isUsed;
Printer() {
this.isUsed = false;
}
public void setUsed(boolean used) {
this.isUsed = used;
}
public boolean isUsed() {
return this.isUsed;
}
}
class Jobs implements Runnable {
String name;
Printer printer;
public Printer getPrinter() {
return printer;
}
public void setPrinter(Printer printer) {
this.printer = printer;
}
boolean isDataAvailble;
Jobs() {
this.isDataAvailble = true;
}
public void setNoData(boolean noData) {
this.isDataAvailble = false;
}
@Override
public void run() {
while (isDataAvailble) {
synchronized (PrinterQueue.printer) {
if (this.printer.isUsed()) {
try {
System.out.println(Thread.currentThread()
+ "WAITING FOR PRINTER");
PrinterQueue.printer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
System.out.println(Thread.currentThread() + "GOT PRINTER");
PrinterQueue.printer.setUsed(true);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
PrinterQueue.printer.setUsed(false);
PrinterQueue.printer.notify();
}
}
}
}
}