Thread.suspend()和.resume()的替代方法 [英] Alternative to Thread.suspend() and .resume()

查看:169
本文介绍了Thread.suspend()和.resume()的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很大一部分代码不是循环的,只是发生一次但要花费一些时间的命令列表.我需要它根据更改的布尔值在任何时候暂停或终止此操作.我可以使用其他线程来挂起,恢复和停止此代码,但是不赞成使用这些方法,因此我想避免使用它们.我可以检查每行代码之间的布尔值,但是我希望有一个更优雅的解决方案.有什么好方法吗?

I have a large segment of code that is not a loop, just a list of commands that happens once but takes some time. I need it to either pause or terminate this at any point based on a changing boolean value. I could use a different thread to suspend, resume and stop this code, but those methods are deprecated, so I would like to avoid using them. I could check the boolean between every line of code, but I am hoping for a more elegant solution. Is there a good way to do this?

推荐答案

自然,使用Thread#interrupt()是处理中断线程(在这种情况下,暂停或停止线程)的正确方法.它的设计使您可以定义安全点,在该安全点处可以中断线程,这对您来说自然是每个任务之间的点.因此,为了避免在每个任务之间手动检查变量,并能够轻松地从上次中断的地方继续工作,可以将任务存储为Runnable的列表,并记住当您在列表中的位置像这样:

The correct way to handle interrupting a thread (in this case, to pause or stop it) is, naturally, with Thread#interrupt(). It is designed so that you can define safe points at which the thread can be interrupted, which for you is naturally the point between each task. So, to avoid having to manually check your variable between each task, and to be able to easily resume where you left off, you can store your tasks as a list of Runnables, and remember your position in the list from when you left off, like this:

public class Foo {
    public static void runTask(Runnable task) throws InterruptedException {
        task.run();
        if (Thread.interrupted()) throw new InterruptedException();
    }
    Runnable[] frobnicateTasks = new Runnable[] {
        () -> { System.out.println("task1"); },
        () -> { Thread.currentThread().interrupt(); }, //Interrupt self only as example
        () -> { System.out.println("task2"); }
    };
    public int frobnicate() {
        return resumeFrobnicate(0);
    }
    public int resumeFrobnicate(int taskPos) {
        try {
            while (taskPos < frobnicateTasks.length)
                runTask(frobnicateTasks[taskPos++]);
        } catch (InterruptedException ex) {
        }
        if (taskPos == frobnicateTasks.length) {
            return -1; //done
        }
        return taskPos;
    }
    public static void main(String[] args) {
        Foo foo = new Foo();
        int progress = foo.frobnicate();
        while (progress != -1) {
            System.out.println("Paused");
            progress = foo.resumeFrobnicate(progress);
        }
        System.out.println("Done");
    }
}
-->
task1
Paused
task2
Done

这篇关于Thread.suspend()和.resume()的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆