Java:如何停止线程?(复制)

时间:2021-06-17 07:11:46

This question already has an answer here:

这个问题已经有了答案:

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.

是否有一种方法可以在没有循环的情况下从内部停止线程?例如,如果您正在下载,理想情况下您希望使用循环,如果我使用循环,我将无法暂停它,直到它到达循环的末尾。

5 个解决方案

#1


25  

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.

这应该工作。

#2


25  

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

我们不会停止或终止线程,而是执行thread . currentthread (). is中断()。

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();

#3


14  

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():

当您想要停止线程时,只需调用一个方法中断():

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-blocking code. 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:

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

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.

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

#4


3  

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)

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

#5


2  

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 recomendation是使用一个共享变量作为一个标志,它要求后台线程停止。然后,该变量可以由另一个请求线程终止的对象来设置。

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

你可以这样杀死另一个进程,然后杀死当前的进程。

#1


25  

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.

这应该工作。

#2


25  

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

我们不会停止或终止线程,而是执行thread . currentthread (). is中断()。

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();

#3


14  

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():

当您想要停止线程时,只需调用一个方法中断():

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-blocking code. 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:

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

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.

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

#4


3  

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)

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

#5


2  

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 recomendation是使用一个共享变量作为一个标志,它要求后台线程停止。然后,该变量可以由另一个请求线程终止的对象来设置。

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

你可以这样杀死另一个进程,然后杀死当前的进程。