来自于:zhangzeyuaaa
一、作用
对于老式的磁带录音机,上面都会有暂停,继续,停止。Thread中suspend,resume,stop方法就类似。
suspend,使线程暂停,但是不会释放类似锁这样的资源。
resume,使线程恢复,如果之前没有使用suspend暂停线程,则不起作用。
stop,停止当前线程。不会保证释放当前线程占有的资源。
二、代码
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10000; i ++) {
System.out.println(i);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.suspend(); //注释1
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.resume(); //注释2
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stop(); //注释3
System.out.println("main end..");
}
代码中注释1的地方,线程会暂停输出,直到注释2处才恢复运行,到了注释3的地方,线程就被终止了。
suspend,resume,stop这样的方法都被标注为过期方法,因为其不会保证释放资源,容易产生死锁,所以不建议使用。
三、如何安全的暂停一个线程
使用一个volatile修饰的boolean类型的标志在循环的时候判断是否已经停止。
public class Test {
public static void main(String[] args) {
Task task = new Task();
new Thread(task).start();
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
task.stop();
System.out.println("main end...");
}
static class Task implements Runnable {
static volatile boolean stop = false;
public void stop() {
stop = true;
}
@Override
public void run() {
int i = 0;
while (!stop) {
System.out.println(i++);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}