gpt4 book ai didi

java - 如何在 IO 操作期间显示进度

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:59 25 4
gpt4 key购买 nike

我想从数组中读取元素并将读取进度显示为并行进程读取。

我有两个内部类:

public class NumbersCounter {

int totalCountOfLines;
int currentCountOfLines = 1;

public NumbersCounter() throws FileNotFoundException, IOException {
new Read();
new Progress();
}

public static void main(String[] args) {
try {
new NumbersCounter();
} catch (FileNotFoundException ex) {
Logger.getLogger(NumbersCounter.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NumbersCounter.class.getName()).log(Level.SEVERE, null, ex);
}
}

class Progress extends Thread {
public Progress() {
start();
}

@Override
public void run() {
synchronized(new Object()) {
while (currentCountOfLines <= totalCountOfLines) {
System.out.println(currentCountOfLines / totalCountOfLines * 100 + "%");
Thread.yield();
}
}
}}

class Read extends Thread {
private FileHandler fh = new FileHandler("ololo.txt");
private String[] lines;

public Read() throws FileNotFoundException, IOException {
this.lines = fh.readFromFile();
start();
}

@Override
public void run() {

totalCountOfLines = this.lines.length;

if (totalCountOfLines > 0) {
synchronized(new Object()) {
for (String line : lines) {
currentCountOfLines++;
Thread.yield();
}

}
} else {
totalCountOfLines = 0;
}
}
}
}

当执行Read Thread的第一步时,我需要执行Progress线程,然后执行Read,然后执行Progress。

最佳答案

使用javax.swing.ProgressMonitorInputStream类作为输入流的包装器,它显示进度对话框。

关于java - 如何在 IO 操作期间显示进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com