事件线程和主线程的代码结构

Code structure for event thread and main thread

如果能给我一些程序设计方面的建议,我将不胜感激。我有一个 swing GUI,我通过以下方式从主启动:

SwingUtilities.invokeLater(new Runnable(){
    public void run(){
        new GUI(generations);
    }
});

但是,由于一些主处理需要一段时间,所以我想在主线程中完成大部分处理(或者可能由主线程启动一个单独的线程?)。我是否需要创建一个 GUI 实例,然后从 main 调用它的方法?

您需要创建 GUI 的初始状态 - 与您现在使用的方法相同,使用空的视觉元素,然后在主线程上计算它们的内容,然后以与 invokeLater().

一个问题是如何从主线程访问 GUI 元素。可能的解决方案如下:

class GUI extends JFrame {
    JTextArea jlist = new JTextArea();

    public GUI(CompletableFuture<GUI> result) {
        this.add(jlist, null);
        result.complete(this);
    }

    public void print(String m) {
        jlist.append(m);
    }

}

public static void main (String[]args) throws Exception {
    CompletableFuture<GUI> result = new CompletableFuture();
    EventQueue.invokeLater(() -> new GUI(result));
    GUI gui = result.get();
    // compute something
    long time = System.currentTimeMillis();
    // pass computed value to GUI
    EventQueue.invokeLater(() -> gui.print("time="+time));
}