在Java上暂停线程 [英] Pausing a Thread on Java

查看:110
本文介绍了在Java上暂停线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出了可运行的内容:

 public class MyRunnable implements Runnable {

     public void run() {
        doA();
        for (i=0; i<18123 ; i++) {
            doB();
        }

        doC();
    }
 }

其中的doA,B,C分别定义了约100行代码.

where doA,B,C are defined with like 100 lines of code each.

使线程处于冻结状态的最佳方法是-在其代码的任何行中-然后从上次停止的代码行继续执行.

what is the best way to make the thread FREEZE - in whatever line of code its at - and then continue from the next line of code where it last stopped.

我正在网上搜索,并且在这里看到 http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html 他们建议使用布尔值,因此,这是否意味着我需要每隔几行代码检查一次布尔值?一定有更好的方法...

I was searching around the net, and I saw here http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html that they suggest on using a boolean, so, does that mean that i need to check that boolean after every few lines of code? there's gotta be a nicer way...

推荐答案

由于不推荐使用Thread.suspend()Thread.resume()的原因,通常无法正常工作

That cannot work in general for the cause Thread.suspend() and Thread.resume() have been deprecated:

Thread.suspend本质上容易死锁.如果目标线程在挂起时在监视器上保持锁以保护关键系统资源,则在恢复目标线程之前,没有线程可以访问该资源.如果将恢复目标线程的线程在调用resume之前尝试锁定此监视器,则会导致死锁.这种僵局通常表现为冻结"进程.

Thread.suspend is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes.

如果您绝对需要这种行为,则必须自己明确实现.

If you absolutely need this behavior, you have to explicitly implemented it yourself.

实现可以如下所示(代码未经测试,也未编译):

The implementations could look like this (code not tested, nor compiled):


public abstract class SafeStoppableRunnable implements Runnable {
    private boolean stopped = false;

    public synchronized void stopSafe() {
        this.stopped = true;
    }

    public synchronized void resumeSafe() {
        this.stopped = false;
        synchronized(this) {
            this.notifyAll();
        }
    }

    protected synchronized void waitWhenStopped() {
        while(this.stopped) {
            this.wait();
        }
    }
}

可停止的Runnable然后应扩展SafeStoppableRunnable并在程序中要使其可停止的所有点调用方法waitWhenStopped().可停止的点可能是程序不拥有全局资源的点,其他线程需要取得进展.

The stoppable Runnables should then extend SafeStoppableRunnable and call the method waitWhenStopped() at all the points in your program you want it to be stoppable. Stoppable points are probably points where the program does not hold global ressources other threads need to make progress.

这篇关于在Java上暂停线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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