How can I interrupt a thread created from within a method?

醉酒当歌 提交于 2020-01-06 20:23:56

问题


I know that you can interrupt a thread created from say a runnable class, but how can I interrupt this thread I created from a method? Using a volatile boolean isn't working for me, so I assume either there is a better way to do this, or I need to somehow interrupt it. I don't want to interrupt all threads, just this one.

I created a method that kicks off a Thread like this:

public static void StartSyncThread() {
        new Thread() {
            public void run() {
                    isRunning = true;  // Set to true so while loop will start

                    while (isRunning) {
                        ...
                        }

            } // Close run()
        }.start();

    }

....

public static void KillSyncThread() {
    isRunning = false;
}

回答1:


If you keep a reference to the thread:

private static Thread myThread;

public static void StartSyncThread() {
    myThread = new Thread() {
        public void run() {    
            while (!Thread.currentThread().isInterrupted()) {
                        ...
            }

        } // Close run()
    }
    myThread.start();
}

then you can call

public static void killSyncThread() {
    if (myThread != null && myThread.isAlive()) {
        myThread.interrupt();
    }
}

to cancel it. This way you can get rid of the static isRunning flag, interrupt() sets a built-in flag that's equivalent to that, plus it will wake the thread up from sleeping or waiting.

If you really did declare the variable as volatile then its updated value should be visible across threads. Could be this is a scoping problem where the flag you're testing isn't the same as what you're setting? With global mutable state it seems likely it could get convoluted fast. Make a small example and verify for yourself that setting the flag or interrupting the thread works, then with that confidence you can look for the real problem.




回答2:


It is possible with your code that the thread will not actually start before you call KillSyncThread. If this is the case then the thread will set isRunning to true and then continue to run forever. I would just set isRunning to true before you start the thread.

It would also fail to stop if the code in the

...

has either an infinite inner loop or a call to a blocking function such as a socket read.



来源:https://stackoverflow.com/questions/32084005/how-can-i-interrupt-a-thread-created-from-within-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!