How can I interrupt a thread created from within a

2019-08-30 03:03发布

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;
}

2条回答
2楼-- · 2019-08-30 03:18

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.

查看更多
地球回转人心会变
3楼-- · 2019-08-30 03:25

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.

查看更多
登录 后发表回答