java暂停其他线程,在Java上暂停线程

本文讨论了如何在Java中安全地暂停和恢复线程,由于`Thread.suspend()`和`Thread.resume()`已被弃用,提出了使用自定义的`SafeStoppableRunnable`抽象类来实现这一功能。通过一个布尔标志和同步方法,可以在不引起死锁的情况下,让线程在特定点暂停并从暂停处继续执行。
摘要由CSDN通过智能技术生成

given a Runnable:

public class MyRunnable implements Runnable {

public void run() {

doA();

for (i=0; i<18123 ; i++) {

doB();

}

doC();

}

}

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.

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...

解决方案

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

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();

}

}

}

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值