exception - JavaFX 线程崩溃

标签 exception hashmap javafx runnable

我有一个 JavaFX 应用程序,它可以在屏幕上为机器人(黑点)设置动画,并在它们去过的任何地方在浅灰色背景上绘制一条小白线(想想 Tron)。为此,我保留了机器人和所有白色像素的所有坐标。机器人的行为由实现 Runnable 的不同线程控制,并且可以在模拟运行时更改。机器人坐标存储在 HashMap 中,坐标是扩展 Point 的类,并使用 double 来提高 x 和 y 值的内部计算精度。对于白点,我使用 HashMap,因为整数精度足以满足它们,因为它们不会移动并无限期地停留在屏幕上的 x 和 y 坐标处。

现在程序运行得很好,但是当存储白点点的 HashMap 增长时,应用程序的 JavaFX 线程崩溃的可能性越来越大(想想看,更具体地说,它只是机器人所在的 Canvas )绘制。)控件的 slider 保持响应,并且迭代的文本字段和 HashMap 的大小不断更新。但没有任何动画,几秒钟后 Canvas 变成白色。增加 Thread.sleep(ms) 的 ms 可以使程序更加稳定,但速度已经非常慢了。而且,这种情况在我的慢速学校上网本(运行 Win XP)上比在我的家用台式电脑(运行 Win7 64 位)上发生得更频繁、更快。异常(exception)也有不同的。对于台式电脑,如下:

java.lang.InternalError: Unrecognized PGCanvas token: 68
at com.sun.javafx.sg.prism.NGCanvas.renderStream(NGCanvas.java:651)
at com.sun.javafx.sg.prism.NGCanvas.renderContent(NGCanvas.java:320)
at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:187)
at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:39)
at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
at com.sun.javafx.sg.prism.NGGroup.renderContent(NGGroup.java:204)
at com.sun.javafx.sg.prism.NGRegion.renderContent(NGRegion.java:420)
at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:187)
at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:39)
at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
at com.sun.javafx.tk.quantum.ViewPainter.doPaint(ViewPainter.java:117)
at com.sun.javafx.tk.quantum.AbstractPainter.paintImpl(AbstractPainter.java:175)
at com.sun.javafx.tk.quantum.PresentingPainter.run(PresentingPainter.java:73)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178)
at com.sun.prism.render.RenderJob.run(RenderJob.java:37)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:98)
at java.lang.Thread.run(Thread.java:724)

对于上网本来说:

java.lang.IllegalArgumentException: alpha value out of range
at java.awt.AlphaComposite.<init>(AlphaComposite.java:624)
at java.awt.AlphaComposite.getInstance(AlphaComposite.java:689)
at java.awt.AlphaComposite.derive(AlphaComposite.java:761)
at com.sun.prism.j2d.J2DPrismGraphics.setExtraAlpha(J2DPrismGraphics.java:569)
at com.sun.javafx.sg.prism.NGCanvas.renderStream(NGCanvas.java:739)
at com.sun.javafx.sg.prism.NGCanvas.renderContent(NGCanvas.java:389)
at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:201)
at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:40)
at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
at com.sun.javafx.sg.prism.NGGroup.renderContent(NGGroup.java:204)
at com.sun.javafx.sg.prism.NGRegion.renderContent(NGRegion.java:420)
at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:201)
at com.sun.javafx.sg.prism.NGNode.doRender(NGNode.java:40)
at com.sun.javafx.sg.BaseNode.render(BaseNode.java:1145)
at com.sun.javafx.tk.quantum.ViewPainter.doPaint(ViewPainter.java:117)
at com.sun.javafx.tk.quantum.AbstractPainter.paintImpl(AbstractPainter.java:182)
at com.sun.javafx.tk.quantum.PresentingPainter.run(PresentingPainter.java:73)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178)
at com.sun.prism.render.RenderJob.run(RenderJob.java:37)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:108)
at java.lang.Thread.run(Thread.java:722)

任何解决或缩小此问题范围的帮助将不胜感激。

编辑: 正如所建议的,我将添加一个仍然存在问题的代码的最小示例。主要方法位于类 Visualizer 中,用于绘制模拟区域

import java.awt.Point;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;

public class Visualizer extends Application {

    private static GraphicsContext gc;
    private static Canvas canvas;
    private static BorderPane pane;
    private static Scene scene;
    private static Thread thread;
    private static Simulator sim = new Simulator();
    private static int optionsWidth = 200;
    private static HashSet<Point> manganCollected = new HashSet<Point>();
    private static HashMap<Integer, Coordinates> coordinates = new HashMap<Integer, Coordinates>();
    private static final int zoom = 4;
    private static Point cmpP;
    /**
     * Height in pixels that's available to draw the simulation on dependent on used monitor resolution 
     */
    public static double simHeight;
    /**
     * Width in pixels that's available to draw the simulation on dependent on used monitor resolution 
     */
    public static double simWidth;


    /**
     * Launches the JavaFX application
     * @param args command line arguments if there are any
     */
    public static void main(String[] args) {
        launch(args);   
    }

    /**
     * Sets up the GUI with all options and the canvas to draw the robots on 
     */
    @Override
    public void start(Stage stage) throws Exception {

        // Determine screen width of the monitor
        Screen screen = Screen.getPrimary();
        Rectangle2D bounds = screen.getVisualBounds();
        double screenHeight = bounds.getHeight();
        double screenWidth = bounds.getWidth();

        // set the stage
        stage.setFullScreen(true);
        stage.setHeight(screenHeight);
        stage.setWidth(screenWidth);
        stage.setTitle("Manganernte");

        // Canvas to draw the simulation on 
        canvas = new Canvas();
        simHeight = screenHeight;
        simWidth = screenWidth - optionsWidth;
        canvas.setHeight(simHeight);
        canvas.setWidth(simWidth);
        gc = canvas.getGraphicsContext2D();
        gc = canvas.getGraphicsContext2D();
        gc.setFill(Color.LIGHTGRAY);
        gc.fillRect(0, 0, simWidth, simHeight);
        gc.setStroke(Color.BLACK);
        gc.setLineWidth(3);
        gc.strokeRect(0, 0, simWidth, simHeight);

        // BorderPane containing the buttons box and the Simulator canvas
        pane = new BorderPane();
        pane.setCenter(canvas);

        // Scene containing the pane
        scene = new Scene(pane);

        // Show the whole stage
        stage.setScene(scene);
        stage.show();
        thread = new Thread(sim);
        thread.start();
    }

    /**
     * Transforms double coordinates as used by the simulator (0/0 in the center) to monitor coordinates (0/0 top left corner)
     * @param coordinates Floating point coordinates that should be transformed
     * @return Coordinates Floating point coordinates that have been transformed
     */
    private static Coordinates transform(Coordinates coordinates) {
        return new Coordinates(Math.round((simWidth / 2) + (zoom * coordinates.getX())), Math.round((simHeight / 2) + (zoom * coordinates.getY()))); 
    }

    /**
     * Transforms integer coordinates as used by the simulator (0/0 in the center) to monitor coordinates (0/0 top left corner)
     * @param Point Integer coordinates that should be transformed
     * @return Point Integer coordinates that have been transformed
     */
    private static Point transform(Point point) {
        return new Point((int)Math.round((simWidth / 2) + (zoom * point.getX())), (int)Math.round(((simHeight / 2) + (zoom * point.getY())))); 
    }

    /**
     * Clear the canvas by drawing a rectangle filled with light gray background
     */
    private static void clear () {
        gc.setFill(Color.LIGHTGRAY);
        gc.fillRect(0, 0, simWidth, simHeight);
        gc.setStroke(Color.BLACK);
        gc.setLineWidth(3);
        gc.strokeRect(0, 0, simWidth, simHeight);
    }

    /**
     * Clears the canvas and then draws first the collected mangan as white rectangles followed by robots as black circles the given coordinates
     * @param redraw boolean that's set to true if iteration hasn't changed but a redraw should be forced anyway (e.g. when simulation is paused and the zoom is used)
     */
    public static void DrawRobots() {
        coordinates = Simulator.coordinates;
        manganCollected = Simulator.manganCollected;
        // clear the canvas with light gray background
        clear();
        // draw harvested mangan as white dots
        gc.setFill(Color.WHITE);
        Iterator<Point> it = manganCollected.iterator(); 
        while(it.hasNext()) {
            cmpP = it.next().getLocation();
            double x = transform(cmpP).getX();
            double y = transform(cmpP).getY();
            gc.fillRect(x, y, zoom, zoom);
        }
        // draw robots
        gc.setFill(Color.BLACK);
        for(int i = 1; i <= coordinates.size(); i++) {
            double x = transform(coordinates.get(i)).getX();
            double y = transform(coordinates.get(i)).getY();
            gc.fillOval(x, y, zoom, zoom);
        }
    }
}

模拟器类:

import java.awt.Point;
import java.util.HashMap;
import java.util.HashSet;

public class Simulator implements Runnable {

    // start variable declarations
    // HashMap of all robot objects the simulator controls
    private static HashMap<Integer, Robot> robots = new HashMap<Integer, Robot>();
    // HashMap of all coordinate objects the simulator controls
    public static HashMap<Integer, Coordinates> coordinates = new HashMap<Integer, Coordinates>();
    // HashMap of all point objects containing the coordinates of places where the mangan has already been collected
    public static HashSet<Point> manganCollected = new HashSet<Point>();
    /**
     * communication radius of the robots according to the requirements
     */
    public static int processSpeed = 100;
    // end variable declarations

    /**
     * Create a robot with x and y
     * @param x x-coordinate
     * @param y y-coordinate
     */
    public static void createRobot(int x, int y) {
        coordinates.put(coordinates.size() + 1, new Coordinates(x, y));
        robots.put(robots.size() + 1, new Robot());
    }

    /**
     * Checks the status, changes it if necessary and acts accordingly
     */
    @Override
    public void run() {
        for(int i = 0; i < 100; i++) createRobot(i - 50, 0);
        Visualizer.DrawRobots();
        while(true) {
            for(int i = 1; i <= robots.size(); i++) robots.get(i).think();
            for(int i = 1; i <= robots.size(); i++) {
                coordinates.get(i).add(robots.get(i).move());
                manganCollected.add(new Point((int)Math.round(coordinates.get(i).getX()), (int)Math.round(coordinates.get(i).getY())));
            }
            Visualizer.DrawRobots();
            try {
                Thread.sleep(processSpeed);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

最后,在这个最小的示例中,机器人类不再做太多事情了:

public class Robot {

    Coordinates future = new Coordinates(0, 0);

    public void think () {
        future.setY(1.0);
    }

    public Coordinates move() {
        return future;
    }
}

更新 刚刚安装了 JDK 8,现在的异常更能说明问题:

Exception in thread "Thread-4" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4

在网上搜索了一下,似乎我需要使用 Platform.runLater() 来避免这种情况发生。但我不知道该怎么做。 我将尝试再次解释我的项目现在的结构:

我有类Visualizer,它扩展了Application,它还包括main()方法,并在GraphicsContext Canvas上绘制UI,包括模拟区域作为灰色矩形。 UI 完成后,它会创建一个实现 RunnableSimulator 类线程。 Simulator 类中的 run() 方法进入 while(true) 循环。只要没有单击任何按钮,循环除了 thread.sleep() 之外什么也不做。如果单击开始按钮,则会执行一些计算,并调用 Visualizer 上的一些方法来在模拟 Canvas 上绘制内容。据我了解,这些调用会导致异常,因为它们是从非 JavaFX 线程发出的。

我是否必须使用 runLater() 来避免此问题,如果是的话,我应该在哪里以及如何执行此操作?

更新2 最终通过将改变 UI/Canvas 任何内容的公共(public)方法的代码包装到 runLater block 中,使其稳定运行(据我现在所知)。

public static void drawStuff() {
    Platform.runLater(new Runnable() {
    @Override
        public void run() {
            // draw stuff
        }
    });
}

最佳答案

只是发布此内容,以便读者立即明显看出该问题实际上有答案/解决方案。

我遇到了同样的问题,正如作者最后指出的那样,他自己是“更新”。

如果您遇到此问题,您可能正在另一个线程中进行 ui Canvas 操作。您应该始终在应用程序线程上执行 ui 操作!使用

Platform.runLater(()->{
    //your code
});

关于exception - JavaFX 线程崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21231557/

相关文章:

android - com.google.gson.stream.MalformedJsonException : Expected ':' at line 1 column 55 path

java - java中以下代码中出现空指针异常的原因是什么?

java - H2 Java Insert ignore - 允许异常

java - java.util.HashMap 中的无限循环

performance - 获取哈希表中键列表的时间复杂度?

Javafx:摆脱 slider margin

java - 在 JavaFX Webview 中运行 URLConnection uc

java - 从嵌套 HashMap 中删除条目时java中的ConcurrentModificationException

java - 使用多线程时如何深度复制 HashMap

JavaFX 13 创建可运行的 jar "no main manifest attribute"