如何在 Nashorn JS 脚本中调用 Thread.sleep
How to call Thread.sleep within Nashorn JS Script
我尝试在 Nashorn 中的各种场合使用 Thread.sleep(),但它要么同时执行,要么抛出异常。我如何在脚本
中使用 Thread.sleep()
这段代码似乎对我有用
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByExtension("js");
int time_in_ms = 3000;
se.put("ms", time_in_ms);
Instant before = Instant.now();
se.eval("java.lang.Thread.sleep(ms)");
Instant after = Instant.now();
System.out.printf("Expected: %dms Actual %dms%n", time_in_ms, Duration.between(before, after).toMillis());
我可以改变 time_in_ms
并获得不同的值,例如
Expected: 3000ms Actual 3195ms
(显然它们是不同的,因为评估 javascript 的开销)
我在 Windows 下尝试使用 JDK1.8 和 JDK11。
我尝试在 Nashorn 中的各种场合使用 Thread.sleep(),但它要么同时执行,要么抛出异常。我如何在脚本
中使用 Thread.sleep()这段代码似乎对我有用
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByExtension("js");
int time_in_ms = 3000;
se.put("ms", time_in_ms);
Instant before = Instant.now();
se.eval("java.lang.Thread.sleep(ms)");
Instant after = Instant.now();
System.out.printf("Expected: %dms Actual %dms%n", time_in_ms, Duration.between(before, after).toMillis());
我可以改变 time_in_ms
并获得不同的值,例如
Expected: 3000ms Actual 3195ms
(显然它们是不同的,因为评估 javascript 的开销)
我在 Windows 下尝试使用 JDK1.8 和 JDK11。