Java:如何停止线程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19894607/
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-12 21:07:10  来源:igfitidea点击:

Java: How to stop thread?

javamultithreading

提问by J Code

Is there any way to stop another thread from OUTSIDE of the thread? Like, if I ran a thread to run that thread and caused that thread to stop? Would it stop the other thread?

有没有办法从线程的外部停止另一个线程?例如,如果我运行一个线程来运行该线程并导致该线程停止?它会阻止另一个线程吗?

Is there a way to stop the thread from inside without a loop? For example, If you are downloading ideally you would want to use a loop, and if I use a loop I wont be able to pause it until it reaches the end of the loop.

有没有办法在没有循环的情况下从内部停止线程?例如,如果您正在理想地下载,您会想要使用循环,如果我使用循环,我将无法暂停它,直到它到达循环结束。

回答by odedsh

The recommended way will be to build this into the thread. So no you can't (or rather shouldn't) kill the thread from outside.

推荐的方法是将其构建到线程中。所以不,你不能(或者更确切地说不应该)从外面杀死线程。

Have the thread check infrequently if it is required to stop. (Instead of blocking on a socket until there is data. Use a timeout and every once in a while check if the user indicated wanting to stop)

如果需要停止,请不经常检查线程。(而不是在有数据之前阻塞套接字。使用超时并每隔一段时间检查用户是否表示想要停止)

回答by Elfentech

JavaSun recomendation is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread to terminate.

JavaSun 建议使用共享变量作为要求后台线程停止的标志。然后可以由请求线程终止的不同对象设置此变量。

You can that way kill the other process, and the current one afterwards.

您可以通过这种方式杀死另一个进程,然后杀死当前的进程。

回答by Fernando

You can create a boolean field and check it inside run:

您可以创建一个布尔字段并在运行中检查它:

public class Task implements Runnable {

   private volatile boolean isRunning = true;

   public void run() {

     while (isRunning) {
         //do work
     }
   }

   public void kill() {
       isRunning = false;
   }

}

To stop it just call

要停止它,只需调用

task.kill();

This should work.

这应该有效。

回答by Trying

We don't stop or kill a thread rather we do Thread.currentThread().isInterrupted().

我们不会停止或杀死线程,而是会这样做 Thread.currentThread().isInterrupted().

public class Task1 implements Runnable {
    public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                       ................
                       ................
                       ................
                       ................
           }
    }
}

in main we will do like this:

主要我们会这样做:

Thread t1 = new Thread(new Task1());
t1.start();
t1.interrupt();

回答by tzima

One possible way is to do something like this:

一种可能的方法是做这样的事情:

public class MyThread extends Thread {
    @Override
    public void run() {
        while (!this.isInterrupted()) {
            //
        }
    }
}

And when you want to stop your thread, just call a method interrupt():

当你想停止你的线程时,只需调用一个方法interrupt():

myThread.interrupt();

Of course, this won't stop thread immediately, but in the following iteration of the loop above. In the case of downloading, you need to write a non-blockingcode. It means, that you will attempt to read new data from the socket only for a limited amount of time. If there are no data available, it will just continue. It may be done using this method from the class Socket:

当然,这不会立即停止线程,而是在上面循环的后续迭代中。在下载的情况下,需要编写非阻塞代码。这意味着,您将仅在有限的时间内尝试从套接字读取新数据。如果没有可用数据,它将继续。可以使用 Socket 类中的这个方法来完成:

mySocket.setSoTimeout(50);

In this case, timeout is set up to 50 ms. After this time has gone and no data was read, it throws an SocketTimeoutException. This way, you may write iterative and non-blocking thread, which may be killed using the construction above.

在这种情况下,超时设置为 50 毫秒。在这段时间过去并且没有读取数据之后,它会抛出一个 SocketTimeoutException。这样,您可以编写迭代和非阻塞线程,这些线程可能会使用上述构造被杀死。

It's not possible to kill thread in any other way and you've to implement such a behavior yourself. In past, Thread had some method (not sure if kill() or stop()) for this, but it's deprecated now. My experience is, that some implementations of JVM doesn't even contain that method currently.

不可能以任何其他方式杀死线程,您必须自己实现这种行为。过去,Thread 有一些方法(不确定是 kill() 还是 stop()),但现在已弃用。我的经验是,JVM 的某些实现目前甚至不包含该方法。