java - JRuby:如果运行时间太长,请关闭 runScriptlet?

标签 java ruby multithreading jruby thread-sleep

我想使用 JRuby 来运行 Ruby 脚本。

但是,我希望如果脚本花费的时间超过 t 秒,它将自动关闭。

这是我的尝试:

ScriptingContainer ruby = new ScriptingContainer();
int t = 3;

new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(t * 1000); // Timeout
                        System.out.println("Timeout passed.");
                        ruby.terminate(); // This has no effect?
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();

Object output = ruby.runScriptlet(scriptWithAnInfiniteLoop);
ruby.terminate(); // Terminate without timeout, at the end of the script

最佳答案

这是使用已弃用 Thread.stop() 的答案:

        ScriptingContainer ruby = new ScriptingContainer();
        int t = 5;

        String script = content;
        Thread runner = new Thread() {
            @Override
            public void run() {
                try {
                    ruby.runScriptlet(script);
                    ruby.terminate(); // Close normally.
                } catch (Exception e) {
                    ruby.terminate(); // Close if JRuby crashes.
                }
            }
        };

        Thread killer = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(t * 1000);
                    runner.stop();
                    ruby.terminate(); // Close forcefully.
                } catch (Exception e) {}
            }
        };

        runner.start();
        killer.start();

请参阅这篇文章,了解它为何被弃用:https://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

由于我使用的是已弃用的方法,因此我不会将此标记为官方答案。

关于java - JRuby:如果运行时间太长,请关闭 runScriptlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56813020/

相关文章:

Ruby:连接和排序文件名

python - 使用 python 和 tkinter 实时绘制串行数据

java - Java Web 应用程序中的唯一序列号

java - 关于从 HTML 中的复选框值更新 MySql 数据库的建议

java - 通过 ACTION_SEND 共享当前 View 而不将图像存储在 android 中

ruby - Redis 命名空间基础知识

ruby - 从两个字符串中删除重复的子字符串

c++ - 被连续迭代的线程安全无序映射

java - 修复线程池: pause until thread available?

java - 实现一个根据值返回对象的工厂