本文介绍了涉及Swing和AWT-EventQueue的无响应线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有反应的应用程序,似乎是一个死锁或者像一个死锁。请参见下面的两个线程。请注意,的调用堆栈上相当远的位置, code>,但我认为这种重构是不可避免的。

This could be arbitrarily difficult if the lock on css> invokeAndWait 中,以便它以正确的顺序执行,但仍然在事件线程上执行? p>

This executes code block 1, handler, and code block 2 in order. If we were to change the invokeAndWait call to invokeLater, the handler would be executed after code block 2. One can easily see that would be a problem for the application. Instead, how about we move code block 2 into the invokeAndWait so that it executes in the right order, but still on the event thread?

synchronized (someObject) {
    // code block 1
}

SwingUtilities.invokeAndWait(Runnable {
    synchronized (someObject) {
        handler();
        // code block 2
    }
});

这是另一种方法。我不知道什么处理程序传递到 invokeAndWait 旨在做。但是它可能需要 invokeAndWait 的一个原因是它从GUI中读取一些信息,然后使用它来更新共享状态。这必须在EDT上,因为它与GUI对象交互,并且不能使用 invokeLater ,因为它将以错误的顺序发生。这建议在进行其他处理之前调用 invokeAndWait ,以便从GUI中读取信息到临时区域,然后使用此临时区域继续执行处理:

Here's another approach. I don't know exactly what the handler passed to invokeAndWait is intended to do. But one reason it might need to be invokeAndWait is that it reads some information out of the GUI and then uses this to update the shared state. This has to be on the EDT, since it interacts with GUI objects, and invokeLater can't be used since it would occur in the wrong order. This suggests calling invokeAndWait before doing other processing in order to read information out of the GUI into a temporary area, then use this temporary area to perform continued processing:

TempState tempState;
SwingUtilities.invokeAndWait(Runnable() {
    synchronized (someObject) {
        handler();
        tempState.update();
    }
);

synchronized (someObject) {
    // code block 1
    // instead of invokeAndWait, use tempState from above
    // code block 2
}

这篇关于涉及Swing和AWT-EventQueue的无响应线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:50