来自于:zhangzeyuaaa
    一、作用
    对于老式的磁带录音机,上面都会有暂停,继续,停止。Thread中suspend,resume,stop方法就类似。
    suspend,使线程暂停,但是不会释放类似锁这样的资源。
    resume,使线程恢复,如果之前没有使用suspend暂停线程,则不起作用。
    stop,停止当前线程。不会保证释放当前线程占有的资源。

    二、代码

    1. public static void main(String[] args) {
    2. Thread thread = new Thread(new Runnable() {
    3. @Override
    4. public void run() {
    5. for (int i = 0; i <= 10000; i ++) {
    6. System.out.println(i);
    7. try {
    8. TimeUnit.SECONDS.sleep(1);
    9. } catch (InterruptedException e) {
    10. e.printStackTrace();
    11. }
    12. }
    13. }
    14. });
    15. thread.start();
    16. try {
    17. TimeUnit.SECONDS.sleep(5);
    18. } catch (InterruptedException e) {
    19. e.printStackTrace();
    20. }
    21. thread.suspend(); //注释1
    22. try {
    23. TimeUnit.SECONDS.sleep(5);
    24. } catch (InterruptedException e) {
    25. e.printStackTrace();
    26. }
    27. thread.resume(); //注释2
    28. try {
    29. TimeUnit.SECONDS.sleep(5);
    30. } catch (InterruptedException e) {
    31. e.printStackTrace();
    32. }
    33. thread.stop(); //注释3
    34. System.out.println("main end..");
    35. }

    代码中注释1的地方,线程会暂停输出,直到注释2处才恢复运行,到了注释3的地方,线程就被终止了。

    1. suspend,resume,stop这样的方法都被标注为过期方法,因为其不会保证释放资源,容易产生死锁,所以不建议使用。

    三、如何安全的暂停一个线程

    使用一个volatile修饰的boolean类型的标志在循环的时候判断是否已经停止。

    1. public class Test {
    2. public static void main(String[] args) {
    3. Task task = new Task();
    4. new Thread(task).start();
    5. try {
    6. TimeUnit.SECONDS.sleep(5);
    7. } catch (InterruptedException e) {
    8. e.printStackTrace();
    9. }
    10. task.stop();
    11. System.out.println("main end...");
    12. }
    13. static class Task implements Runnable {
    14. static volatile boolean stop = false;
    15. public void stop() {
    16. stop = true;
    17. }
    18. @Override
    19. public void run() {
    20. int i = 0;
    21. while (!stop) {
    22. System.out.println(i++);
    23. try {
    24. TimeUnit.SECONDS.sleep(1);
    25. } catch (InterruptedException e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. }
    30. }
    31. }