Ant*_*rev 5 java multithreading kotlin
假设我使用 IBM 创建的 jar。假设这个 Jar 具有我需要的功能,但最终是这样构建的:
while (true) {
System.out.println(1)
}
Run Code Online (Sandbox Code Playgroud)
(当然,它实际上并不只是打印 1,但对于这个例子来说,我们可以说它是)所以,我使用 future 调用了在另一个线程中执行此操作的函数。如何才能完全杀死运行该代码的线程?或者,我如何终止 Kotlin 中运行代码的异步任务。
Kotlin 或 Java 的解决方案会很棒,提前致谢!
编辑:
我发现,如果这是一个线程,我可以Thread#stop()让它真正停止。但不幸的是,使构造函数多次抛出异常,会导致 JVM 从内存中删除该类,从而导致NoClassDefFoundError下次实例化该类时出现错误。
如果您可以捕获它的线程,只要它在内部执行某种阻塞功能,您就应该能够杀死它。
class OtherFunction implements Runnable {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// We assume the thread will exit when interrupted.
System.out.println("Bye!!");
return;
}
System.out.println("Hello");
}
}
}
class Killable implements Runnable {
final Runnable target;
private Thread itsThread;
Killable(Runnable target) {
this.target = target;
}
@Override
public void run() {
// Catch the thread id of the target.
itsThread = Thread.currentThread();
// Launch it.
target.run();
}
public void kill() {
// Give it a good kick.
itsThread.interrupt();
}
}
public void test() throws InterruptedException {
OtherFunction theFunction = new OtherFunction();
Killable killableVersion = new Killable(theFunction);
new Thread(killableVersion).start();
// Wait for a few seconds.
Thread.sleep(10000);
// Kill it.
killableVersion.kill();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4104 次 |
| 最近记录: |