多线程Java脚本引擎



我有一个为每个线程创建的脚本引擎。问题是每个线程都在等待其他线程完成。线程应该是异步运行的。当我注释出ScriptEngine.eval()行的位置时,代码的运行方式就像应该一样

启动线程每次大约创建57个线程。

for (CalculationThread calcThread : this.calcThreads) {
    calcThread.start();
}

为每个线程创建一个脚本管理器和脚本引擎。脚本引擎正在求解一个43.0*0.76282-0.154的方程。这是一个非常简单的方程式。

ScriptEngineManager mgr = new ScriptEngineManager();
        for (ScriptEngineFactory sef : mgr.getEngineFactories()) {
            if (sef.getParameter("THREADING") == null) {
                System.out.println("this is not thread safe: " + this.threadName);
            } else {
                System.out.println("This is thread safe: " + this.threadName);
            }
        }
        ScriptEngine engine = mgr.getEngineByName("js");
        String modText = this.equationCalculation.getEquation();
        for (int i = this.counter; i < this.counter + this.equationCalculation.getTileSize(); i++) {
            String tempModText = "";
            boolean noData = false;
            boolean cannot = false;
            tempModText = modText;
            for (int j = 1; j < this.equationCalculation.getImages().size(); j++) {
//              code that does stuff in the loop
            }

            //Code that does other stuff
                    try {
                        Number theNumber = (Number) engine.eval(tempModText);
                        this.equationCalculation.setOutputAtIndex(0,i,theNumber.floatValue());
                    } catch (ScriptException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        this.equationCalculation.setOutputAtIndex(0,i,0);
                    }
            }
        }

我的问题是,我是否错误地实现了脚本引擎?当我注释出脚本引擎评估字符串的位置时,运行需要20秒才能抛出5400万像素,但当离开脚本引擎时,需要21分钟

另一个问题是,脚本引擎只是为了实现我想要它做的事情而放慢速度吗

请不要留下评论,说你是如何使用脚本引擎来解决这个方程的

这里的问题是您使用的是脚本引擎。计算字符串需要一段时间,我认为你对每个像素都这样做。尽量不要在每次使用脚本时都对其进行评估。可以预先编译脚本。看看这篇文章:https://stackoverflow.com/questions/12220267/with-java-scriptengine-groovy-how-to-make-it-more-performant

最新更新