gpt4 book ai didi

java - 在主线程中完成工作之前,线程中的进度条不会更新其 UI

转载 作者:行者123 更新时间:2023-12-01 06:14:52 32 4
gpt4 key购买 nike

我正在将一个大文件切割成 block ,并希望显示进度。当我点击 startCut 按钮时,这里是要执行的代码:

FileInputStream in = new FileInputStream(sourceFile);
int blockSize = (int)(getSelectedBlockSize() * 1024);
int totalBlock = Integer.parseInt(txtNumberOfBlock.getText());
byte[] buffer = new byte[blockSize];
int readBytes = in.read(buffer);
int fileIndex = 1;

class PBThread extends Thread
{
@Override
public void run()
{
while(true)
{
pbCompleteness.setValue(value);
//value++; //place A
System.out.println(value);
if (value >= 100)
break;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
value = 0;
PBThread pbThread = new PBThread();
pbThread.start();
while(readBytes != -1)
{
File file = new File(targetFilePath + fileIndex);
FileOutputStream out = new FileOutputStream(file);
out.write(buffer, 0, readBytes);
out.close();
value = (int)(fileIndex / (double)totalBlock * 100);// place B
readBytes = in.read(buffer);
fileIndex++;
}

我在 B 处的运行方法之外更改了进度条的值,问题是——进度条只显示两个状态:0% 和 100%。 但是,如果我拿走 B 处的代码,并更改 A 处运行方法内的进度条的值,问题就会消失。 我知道也许用 SwingWorker 它可以很容易地修复,但我确实想知道为什么会这样,虽然我改变了运行方法的值,当我在运行方法中打印出来时,它确实变了。 如何在运行方法之外更改值时解决该问题?

最佳答案

问题的症结在于您正在更新组件:pbCompleteness事件调度线程 之外的线程上。您可以使用 SwingUtilities.invokeLater 补救此问题从你的 run() 方法中;例如

AtomicInteger value = new AtomicInteger(0);
while (true) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
pbCompleteness.setValue(value.get());
}
});

// Do some work and update value.
}

这将导致 JProgressBar 在您的工作线程继续运行时在事件调度线程上更新(并重新绘制)。请注意,为了在“内部”匿名 Runnable 实例中引用 value,我已将其更改为 AtomicInteger。这也是可取的,因为它使线程安全。

关于java - 在主线程中完成工作之前,线程中的进度条不会更新其 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7874582/

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