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 引擎來實現的。在實際應用中,你可能需要根據具體需求選擇合適的方法。