Swing中的背景线程

时间:2011-03-28 00:50:48

标签: java multithreading swing swingworker worker

我很茫然,简单地使用摇摆工人。 我在doInBackground()中添加了一些简单的代码,但它没有执行,我没有收到异常。当我使用debuger时,他正在按照自己的意愿工作。 )) 可能有人有这样的事情,或告诉我如何缓存这个错误的想法,或者...... 对不起,代码很复杂。告诉我你需要更多的东西或评论。 如果我删除“installer.setFPS(fPSCalculatorGhost.getFPS());” - 字符串,一切都会好的。

    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new MainWindow().setVisible(true);
        }
    });


public MainWindow() {
    initComponents();
}


private void initComponents() {
    InterfaceUpdateWorker interfaceUpdate = new InterfaceUpdateWorker(
            new InterfaceInfoInstallerImpl());
    interfaceUpdate.setCamera(gLEventListenerImpl.getCameraGhost());
    interfaceUpdate.setfPSCalculatorGhost(gLEventListenerImpl.getFPSCalculatorGhost());
    interfaceUpdate.execute();
}
@Override
protected Void doInBackground() throws InterruptedException {
    while(true) {
        installer.setFPS(fPSCalculatorGhost.getFPS());
        installer.setCameraXPosition(
                cameraGhost.getCameraXPosition());
        installer.setCameraYPosition(
                cameraGhost.getCameraYPosition());
        installer.setCameraZPosition(
                cameraGhost.getCameraZPosition());
        Thread.sleep(200);
    }
}
public final class FPSCalculatorGhost {

    private FPSCalculatorGhost() {
    }

    public float getFPS() {
        return fpsTask.getAvrfps();
    }
}

public float getAvrfps() {
    synchronized (this) {
    return avrfps;
    }
}

一切都围绕着fpsTask-object。它由interfaceUpdate-thread(或应用程序工作者线程)使用,并由初始化的其他线程使用。 结果: 1)。 fpsTask-object在一个线程中初始化 2)。 fpsTask-object为另一个线程提供值。

当我从FPSCalculatorGhost最终制作fpsTask时,它开始起作用。

1 个答案:

答案 0 :(得分:1)

所以,问题是installer.setFPS(fPSCalculatorGhost.getFPS());行。它有什么作用? 它调用getAvrFPS方法,其中包含此块:

synchronized (this) {
   return avrfps;
}

只有在同一个对象的某个同步块或同步方法中没有其他线程同时,才能输入此synchronized块。在您发布的代码段中没有这样的块/方法,因此您必须自己搜索。

最重要的是,确保持有锁的其他线程没有等待来自此工作线程的某些结果。

当您遇到死锁时,使用java进程的进程ID运行jstack以获取所有线程运行的堆栈跟踪 - 这包括它们持有和等待的锁。 (jps为您提供所有Java进程ID。)