Stopping a Thread in Java?

后端 未结 6 2000
耶瑟儿~
耶瑟儿~ 2020-11-30 06:46

I\'m in the process of writing a piece of code that connects to a server spawns a bunch of threads using that connection and does a bunch of \"stuff\".

There are cer

相关标签:
6条回答
  • 2020-11-30 07:29
    private Thread m_CleanupThread = null; 
    
    public void threadCleanUp(){
        m_CleanupThread = new Thread(this);
        m_CleanupThread.Start();
    }
    

    This thread will terminate and garbage collector will do the rest.

    0 讨论(0)
  • 2020-11-30 07:33

    Look here :

    Suggested Methods for Stopping a Thread in HowToStopAThread

    0 讨论(0)
  • 2020-11-30 07:41

    Assuming your threads are reasonably under your control - i.e. they're not calling anything which is going to potentially wait forever without your code executing - I would shut it down with a simple (but thread-safe - use volatile!) flag.

    See this article for an example in C# - the Java equivalent should be easy to work out. Calling interrupt won't have any effect until the thread next waits, and stop can leave your app in a hard-to-predict state. Wherever possible, go for a clean, orderly shutdown instead.

    0 讨论(0)
  • 2020-11-30 07:42

    There is an question with a very similar topic:

    How to abort a thread in a fast and clean way in java

    0 讨论(0)
  • 2020-11-30 07:44

    Use your_thread.interrupt and check in your thread if Thread.interrupted() return true. If so, close your thread properly.

    0 讨论(0)
  • 2020-11-30 07:44

    I've used this very simply example pattern. It seems to work and is easy to understand and implement.

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