我的申请有点问题。
我有3个主题:Main,Producer - 读取一些文件和Consumer - 逐行显示文件;
这里的电源类的简短版本:
MAIN.class
for (int i = 0; i < args.length; i++) {
List<Thread> threadList = new ArrayList<Thread>();
String file = args[i];
int queueSize = 10;
int waitTime = 200;
BlockingQueue queue = new LinkedBlockingQueue(queueSize);
Reader reader = (Reader) context.getBean("reader");
Writer writer = (Writer) context.getBean("writer");
Handler handler = (Handler) context.getBean("Handler", writer, reader, queueSize);
Producer producer = (Producer) context.getBean("Producer", handler, queue, waitTime);
Consumer consumer = (Consumer) context.getBean("Consumer", handler, queue, waitTime);
handler.setFile(file, extension.get(0));
threadList.add(new Thread(producer, "Producer"));
threadList.add(new Thread(consumer, "Consumer"));
for (Thread thread : threadList) {
thread.start();
}
for (Thread thread : threadList) {
try {
thread.join();
} catch (InterruptedException e) {
System.err.println("Interrupted Exception thrown by : " + thread.getName());
}
}
} else break;
}
HANDLER.class
public Handler(Writer writer, Reader reader, int count) {
this.reader = reader;
this.writer = writer;
queue = new LinkedBlockingQueue(count);
}
public void getHandle(LinkedList list) {
writer.Printer(list);
}
public LinkedList setHandle(String string, int line) {
reader.objectReader(string, getFileName(), line);
return reader.getList();
}
CONSUMER.class
public Consumer(Handler handler, BlockingQueue queue, int waitTime) {
this.queue = queue;
this.handler = handler;
this.waitTime = waitTime;
}
@Override
public void run() {
while (!isEnd()) {
try {
handler.getHandle(queue.poll(waitTime, MILLISECONDS));
} catch (Exception e) {
System.err.println(e);
}
}
}
private boolean isEnd() {
if (queue.isEmpty() && handler.isFileEnd()) {
return true;
} else {
return false;
}
}
PRODUCER.class
public Producer(Handler handler, BlockingQueue queue, int waitTime) {
this.queue = queue;
this.handler = handler;
this.waitTime = waitTime;
}
@Override
public void run() {
try {
if (handler.getFileExtension().equals("xlsx")) {
xlsxCheck(handler.getFile());
} else {
Stream stream = Files.lines(getFilePath());
Iterator iterator = stream.iterator();
String string = (String) iterator.next();
while (string != null) {
queue.offer(handler.setHandle(string , i), waitTime, MILLISECONDS);
if (!iterator.hasNext()) {
setFileEnd(true);
System.out.println("produce stop");
Thread.sleep(100);
break;
}
string = (String) iterator.next();
i++;
}
}
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
我的第一个问题是Producer和Main类在WAIT状态下处于消费者状态时停止,但我用BlockingQueue的poll()方法解决了它。 第二个是当我读取文件时,我在我的控制台中看到了这些行:
很好。
但之后,我看到了
错误的是我只有8次最后一行。而且我不明白为什么。
任何人都可以帮助我吗?
答案 0 :(得分:0)
这是一个奇怪的但它需要在reader.objectReader()中读取文件的每一步创建新的List;