在 Java 中停止线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/247455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:59:45  来源:igfitidea点击:

Stopping a Thread in Java?

javamultithreading

提问by Omar Kooheji

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 certain instances where the connection fails and I need to stop everything and start from scratch with a new object.

在某些情况下,连接失败,我需要停止一切并从头开始使用新对象。

I wanted to clean up after the object but calling thread.stop on the threads, but this method is seemingly deprecated.

我想在对象之后清理但在线程上调用 thread.stop,但这个方法似乎已被弃用。

What is the recommended alternative to doing this? Should I write my own cleanup and exit method for each of the threads? Set the thread to null? or something else?

这样做的推荐替代方法是什么?我应该为每个线程编写自己的清理和退出方法吗?将线程设置为空?或者是其他东西?

采纳答案by Blauohr

Look here :

看这里 :

Suggested Methods for Stopping a Thread in HowToStopAThread

HowToStopAThread 中停止线程的建议方法

回答by gizmo

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

如果 Thread.interrupted() 返回 true,请使用 your_thread.interrupt 并检查您的线程。如果是这样,请正确关闭您的线程。

回答by Jon Skeet

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.

假设您的线程合理地在您的控制之下 - 即它们不会调用任何可能在没有您的代码执行的情况下永远等待的东西 - 我会用一个简单的(但线程安全的 - 使用 volatile!)标志关闭它。

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

请参阅本文以获取 C# 示例 - Java 等效项应该很容易计算。interrupt在线程下一次等待之前调用不会产生任何影响,并且stop会使您的应用程序处于难以预测的状态。在可能的情况下,改为进行干净、有序的关机。

回答by dmeister

There is an question with a very similar topic:

有一个主题非常相似的问题:

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

如何在java中以快速干净的方式中止线程

回答by Brian Sweeney

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

我使用了这个非常简单的示例模式。它似乎有效并且易于理解和实施。

回答by Arun Edwin

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.

该线程将终止,垃圾收集器将完成剩下的工作。