Javafx线程崩溃



我有一个javafx应用程序,该应用程序在屏幕上对机器人(黑点)进行动画,并在他们去过任何地方的Lighgray背景上绘制了一条小小的白色线(想想Tron)。为此,我保留了机器人和所有白色像素的所有坐标。机器人的行为由其他可运行的线程控制,并且在模拟运行时可以更改。机器人坐标存储在一个哈希图中,坐标为bee bee bee bee bee tops延长点并使用双倍的x和y值进行更高的内部计算精度。对于白点,我正在使用hashmap,因为整数精度对它们来说足够了,因为它们不移动并留在屏幕上的X和y坐标上。

现在,该程序运行良好,但是当hashmap存储白点的要点时,越来越有可能崩溃应用程序的Javafx线程(开始考虑一下,更具体地说,它是机器人所在的帆布绘制。但是什么都没有动画,几秒钟后,画布变白了。增加螺纹的MS.sleep(MS)使该程序更加稳定,但疼痛的速度非常慢。同样,它在我的学校慢上书本(跑步XP)上比在我的家庭桌面PC(运行Win7 64bit)上更频繁地发生。例外也是一个例外。对于桌面PC,如下:

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)

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

编辑:正如建议的那样,我将添加一个最小的代码示例,这些示例仍然显示出该问题。主要方法在于绘制模拟区域的类可视化器

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()避免这种情况。但是我不确定该怎么做。我将尝试再次解释我的项目现在如何结构:

我有class 可视化器扩展了 application ,其中还包括main()方法,并在GraphicsContext Canvas上绘制了UI(包括仿真区域)作为灰色矩形。完成UI后,它会创建一个实现 Runnable 的类 simulator 的线程。 simulator 类中的run()方法它输入了一段时间(true)循环。只要没有单击按钮,循环除了线程()外什么都没有。如果单击"开始"按钮,则执行一些计算,并在可视化器上使用某些方法将其绘制在仿真画布上的东西。我的理解是,这些呼叫会导致例外,因为它们是由非Javafx线程制成的。

我是否必须使用Runlater()来避免此问题,如果是这样,我该怎么办?

更新2 终于通过将所有关于UI/Canvas的公共方法包装到Runlater Block中,例如。

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

只是发布此信息,因此读者很明显问题实际上具有答案/解决方案。

我遇到了同样的问题,正如作者最终指出的那样,以"更新"。

如果您有这个问题,则可能是在另一个线程中进行UI帆布操作。您应该在应用程序线程上始终进行UI操作!使用

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

最新更新