JavaScriptEngineManager 本身并不直接支持多线程,因为它是一个单例类。但是,你可以通过以下方法在 Java 中使用 JavaScriptEngineManager 支持多线程:
ScriptEngine
实例。import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class MultiThreadedJavaScript {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
Runnable task = () -> {
try {
engine.eval("print('Hello from thread ' + Thread.currentThread().getName() + ')');
} catch (ScriptException e) {
e.printStackTrace();
}
};
Thread thread1 = new Thread(task, "Thread-1");
Thread thread2 = new Thread(task, "Thread-2");
thread1.start();
thread2.start();
}
}
ThreadLocal
类为每个线程创建一个单独的 ScriptEngine
实例。import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class MultiThreadedJavaScript {
private static final ThreadLocal<ScriptEngine> engineThreadLocal = new ThreadLocal<>();
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
Runnable task = () -> {
ScriptEngine engine = engineThreadLocal.get();
if (engine == null) {
engine = manager.getEngineByName("nashorn");
engineThreadLocal.set(engine);
}
try {
engine.eval("print('Hello from thread ' + Thread.currentThread().getName() + ')");
} catch (ScriptException e) {
e.printStackTrace();
} finally {
engineThreadLocal.remove();
}
};
Thread thread1 = new Thread(task, "Thread-1");
Thread thread2 = new Thread(task, "Thread-2");
thread1.start();
thread2.start();
}
}
请注意,这些方法并不是 JavaScriptEngineManager 的直接多线程支持,而是通过在多线程环境中使用 JavaScript 引擎来实现的。在实际应用中,你可能需要根据具体需求选择合适的方法。