我有一个类Producer
和一个类Printer
。 生产者从文件数据中读取以创建PrinttJobs
对象。 A Producer
生成一个PrintJob
并添加到Queue
,通知Printer
。 Producer
比等待1 - 5秒创建新的PrintJobs
。 当Printer
不满足时,它打开并从队列中获取作业并打印它们。在此期间Producer
无法正常工作。 Printer
打印所有内容并再次等待,让Producer
重新工作。 该应用程序适用于2个生产者和1个打印机。 我的问题是,有时候它会很好,有时候它不打印所有东西。此外,我认为我的wait
与时间限制1-5秒是行不通的/可能是问题。代码如下:Java - 线程问题
EDITED
当制片实际产生的东西,他们在同一时间发送几乎总是。有时它会停止生成,但仍然是文件中的数据。
class Printer implements Runnable {
protected long MILLIS_PER_PAGE = 500;
private String name;
Queue queue;
boolean lock = false;
public Printer(String name, Queue queue) {
this.name = name;
this.queue = queue;
}
public String getPrinterName() {
return name;
}
@Override
public void run() {
System.out.println("["+getPrinterName()+"] Ligando...");
while(true) {
synchronized(this){
if(queue.isEmpty()) {
try {
System.out.println("["+getPrinterName()+"] Esperando por tabalho de impressão...");
lock = false;
halt();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
lock = true;
PrintJob pj = queue.removeFront();
System.out.println("Imprimindo "+ pj.getJobName());
try {
wait(pj.getNumberOfPages() * MILLIS_PER_PAGE);
System.out.println(pj.getJobName() + " ok.");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public void halt() throws InterruptedException {
wait();
}
}
`
`
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
class Producer implements Runnable {
private String name;
Queue queue;
String job;
int pags;
String arquivo;
public Producer(String name, Queue queue, String arquivo) {
this.name = name;
this.queue = queue;
this.arquivo = arquivo;
}
public String getProducerName() {
return name;
}
@Override
public void run(){
synchronized (PrinterApp.printer) {
FileReader fin;
try {
fin = new FileReader(arquivo);
Scanner src = new Scanner(fin);
while (src.hasNext()) {
if (PrinterApp.printer.lock == true){
PrinterApp.printer.wait();
}
job = src.next();
pags = src.nextInt();
PrintJob p = new PrintJob(job, pags);
queue.addBack(p);
System.out.println("["+getProducerName()+"] produzindo arquivo " + job +", número de páginas: " + pags);
PrinterApp.printer.notify();
PrinterApp.printer.wait(1000 + (int)Math.round((Math.random() * (5000 - 1000))));
}
fin.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (QueueException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
看起来极像是从操作系统级的任务,我花了一年多以前 – Woot4Moo