关于Thread对象的suspend,resume,stop方法

1、做用java

    对于老式得磁带录音机,上面都会有,暂停,继续,中止。Thread中suspend,resume,stop方法就相似。安全

    suspend,使线程暂停,可是不会释放相似锁这样的资源。ide

    resume,使线程恢复,若是以前没有使用suspend暂停线程,则不起做用。spa

    stop,中止当前线程。不会保证释放当前线程占有的资源。线程

2、代码code

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的地方,线程就被终止了。orm

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

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

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

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();
                }
            }
        }
    }
}
相关文章
相关标签/搜索