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

前端 未结 2 897
孤街浪徒
孤街浪徒 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:34

    Well I red a bit of the documentation about why stop() is deprecated and here is the most relevant part :

    This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply m>odifies 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. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait.

    With those details, I think there is no more a simple way to stop all the threads as stop() did. You might need to modifie the threads so that you have a way to stop them (if it is possible for you).

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题