gpt4 book ai didi

java - 如何编写多线程代码来加速繁重的重复性任务?

转载 作者:行者123 更新时间:2023-12-02 01:31:48 24 4
gpt4 key购买 nike

我有一个 swing 应用程序,启动速度非常慢,因为它必须将一千张图片加载到 GUI 中。启动需要10秒。

这是一个单线程应用程序,我如何编写多线程来加速任务?以下代码位于 1000 次迭代的 for 循环中。

    ImageIcon icon = new ImageIcon(Files.readAllBytes(coverFile.toPath()));
// ImageIcon icon = createImageIcon(coverFile);
JLabel label = null;
if (coverCount % 2 == 0) {
label = createLabel(coverFile, movieFile, icon, SwingConstants.LEFT);
} else {
label = createLabel(coverFile, movieFile, icon, SwingConstants.CENTER);
}
box.add(label);

图像正在按顺序加载并放入 Box 中。如果我想进行多线程,我有两个困难

  1. 线程如何将值返回给父级
  2. 如何实现非阻塞回调,将图片添加到按顺序装箱

谢谢。

最佳答案

How does a thread return value to parent

使用回调机制。对于 Swing,这意味着使用 SwingWorker 并在工作线程的 done() 中通知 GUI 线程完成情况。方法或通过向工作人员添加 PropertyChangeListener,监听工作人员的“状态”属性,以了解其何时更改为 SwingWorker.StateValue.DONE

How to achieve non-blocking call back which add the image to the box sequentially

SwingWorker 有一个发布/处理方法对,允许通过发布方法从后台线程顺序发送数据,然后在处理方法内的事件线程上顺序处理数据。这需要使用 SwingWorker<VOID, Image>SwingWorker<VOID, Icon>或类似的东西,第二个通用参数指示通过此机制发送的对象的类型。

例如:

public class MyWorker extends SwingWorker<Void, Icon> {
@Override
protected Void doInBackground() throws Exception {
boolean done = false;
while (!done) {
// TODO: create some_input here -- possibly a URL or File
Image image = ImageIO.read(some_input);
Icon icon = new ImageIcon(image);
publish(icon);

// TODO: set done here to true when we ARE done
}
return null;
}

@Override
protected void process(List<Icon> chunks) {
for (Icon icon : chunks) {
// do something with the icon here
// on the event thread
}
}
}

并在 GUI 中使用它:

// may need constructor to pass GUI into worker
final MyWorker myWorker = new MyWorker();
myWorker.addPropertyChangeListener(evt -> {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
// We're done!
// call get to trap errors
try {
myWorker.get();
} catch (InterruptedException | ExecutionException e) {
// TODO: real error handling needed here
e.printStackTrace();
}
}
});
myWorker.execute(); // start worker in a background thread

有关 Swing 并发的更多信息,请查看 Lesson: Concurrency in Swing

关于java - 如何编写多线程代码来加速繁重的重复性任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55921001/

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