How I can replace deprecated method this.stop() in ThreadGroup

前端 未结 2 918
孤街浪徒
孤街浪徒 2021-01-17 02:49

I am working on java version upgrade project and I am on the work where I need to replace deprecated methods.

this.stop();

2条回答
  •  心在旅途
    2021-01-17 03:47

    There is no single method that replaces stop() from Thread Group but rather a design approach

    From the oracle documentation it says

    Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running

    Looking at the samples on What should I use instead of Thread.stop?

    private volatile Thread blinker;
    
    public void stop() {
        blinker = null;
    }
    
    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }
    

    Throughout your thread, you need to check on a thread safe variable (in the example above its blinker) ... when stop is called, it sets the thread to null breaking out of the while loop and returning from run... thereby "stopping" the thread

提交回复
热议问题