如何按需立即终止无监督脚本?
我有一个类似于解释器的 GUI。它允许用户用 Jython(Python 在 Java 中的实现)编写脚本并随时运行它。除此之外,我还希望允许用户随时终止运行。
问题是,我真的不知道该怎么做。该脚本正在不同的线程上运行,但我不知道有什么安全方法可以在运行过程中停止/中断/终止线程,更不用说不知道线程/脚本正在运行什么(它可能是一项简单的任务,也可能是针对数据库的某种繁重的 SQL 查询,而数据库需要仔细的资源处理)。
我怎样才能立即终止这种按需运行?
I have a GUI which resembles an interpreter. It allows the user to write a script in Jython (implementation of Python in Java) and run it whenever he wants. Apart from that, I also wish to allow the user to instantly terminate the run whenever he wants.
Thing is, I don't really know how to do it. The script is being run on a different Thread, but I don't know of any secure way to stop/interrupt/terminate a thread in the middle of its run, let alone not knowing what is being run by the thread/script (it could be a simple task or maybe some sort of a heavy SQL query against a DB, and a DB is something which requires careful resource handling).
How can I instantly terminate such run on demand?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,没有安全的方法可以立即安全地终止线程。这就是 Thread.stop 被弃用的部分原因。
这是一个复杂的问题,它实际上取决于您的线程如何工作。不存在让所有线程执行此操作的通用解决方案。听起来您的线程不在循环中,因此在循环中轮询变量是行不通的。但您也许可以采取变体:
作为最后的手段,您仍然可以使用已弃用的 Thread.stop,但它是不安全的,应尽可能避免。除此之外,也许您可以执行进程分叉并在操作系统级别手动处理它,但这不太像java。
Unfortunately there is no safe way to terminate a thread instantly and safely. That is part of the reason why Thread.stop has been deprecated.
It is a complicated problem, and it really depends on how your thread works. A generic solution for all threads to do this does not exist. It sounds like your thread is not in a loop, so polling a variable on a loop will not do. But you may be able to a variation:
As a last resort you can still use the deprecated Thread.stop, but it will be unsafe and should be avoided if at all possible. Other then that maybe you can do a process fork and handle it manually at the OS level, but that is not very java like.