【问题标题】:Java stop thread all threads running from classJava停止线程从类运行的所有线程
【发布时间】:2012-12-24 04:28:17
【问题描述】:

我需要做的是能够停止从一个实现可运行的线程类运行的所有线程。这就是我的意思:这是我的“线程”类的开始:

public class HTTP extends Thread
{   
    int threadNumber;
    String host;
    int port;
    int timeLeft;
    private BufferedReader LocalBufferedReader;

    public HTTP(int threadNumber, String host, int port, int timeLeft)
    {
        this.threadNumber = threadNumber;
        this.host= host;
        this.port = port;
        this.timeLeft = (timeLeft * 1000);
    }

  public void run()
  {

这就是我创建多个线程来执行此操作的方式:

 for (int n = 1; n <= m; n++) {
      new HTTP(n + 1, str, j, k).start();
    }

m 是要创建的线程数。这可以是50-1000之间的任何地方。现在我需要做的就是立即停止所有这些。我怎样才能做到这一点?

【问题讨论】:

  • 那是邪恶的,不要那样做。
  • 最好的办法是有一个线程池来轮询HTTP对象(或者使用select和非阻塞io),每个HTTP方法的update方法会快速更新连接状态并返回。跨度>
  • 更好的是使用现成的http服务器实现。

标签: java


【解决方案1】:

先存储所有线程:

ArrayList<Thread> threads = new ArrayList<Thread>();
for (int n = 1; n <= m; n++) {
    Thread t = new HTTP(n + 1, str, j, k);
    threads.add(t);
    t.start();
 }

现在对于stop 方法,只需循环所有线程并对其调用中断:

for(Thread thread : threads)
{
    thread.interrupt();
}

确保在您的 HTTP 线程中检查 isIntruppted()。所以你会做这样的事情:

public class InterruptTest {

    static class TThread extends Thread {
        public void run() {
            while(!isInterrupted()) {
                System.out.println("Do Work!!!");
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread t = new TThread();
        t.start();

        Thread.sleep(4000);
        System.out.println("Sending interrupt!!");
        t.interrupt();
        Thread.sleep(4000);
    }

}

【讨论】:

  • 我们只希望线程上没有阻塞 IO。
  • 我试过了,它不起作用。它设置为在 for 循环之后打印“线程停止”。它打印已停止的线程,但这些线程上的函数仍在运行。我也试过 thread.stop()
  • @user1947236 您需要在线程的实际实现中继续检查“Thread.interrupted()”。检查我上面的例子。
【解决方案2】:

在 Java 中停止线程是一个通过中断实现的协作过程。您可以存储您的线程并一一中断它们:

List<Thread> threads = new ArrayList<> ();

for (int n = 1; n <= m; n++) {
  Thread t = new HTTP(n + 1, str, j, k);
  threads.add(t);
  t.start();
}

//later on

for (Thread t : threads) {
    t.interrupt();
}

不过,有几点值得注意:

  • 只有当您的 run 方法通过停止正在执行的操作来对中断做出反应时,这才有效
  • 您可以使用线程池更轻松地执行相同的操作,例如使用Executors 类提供的各种工厂方法返回的ExecutorService 之一。他们确实会为您处理线程的生命周期。

【讨论】:

    【解决方案3】:

    首先,启动 1000 个线程实际上是没有意义的,因为其中很少有会被安排实际并发运行。

    其次,您不能“停止”线程。你所能做的就是通过合作代码很好地要求他们停止。

    最简单的方法是关闭 JVM。

    【讨论】:

      猜你喜欢
      • 2013-03-31
      • 1970-01-01
      • 2019-08-08
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      相关资源
      最近更新 更多