7

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

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之间的任何地方。现在我需要做的就是立即停止所有这些。我怎样才能做到这一点?

4

3 回答 3

9

首先存储所有线程:

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

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

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

}
于 2013-01-09T21:31:51.670 回答
3

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

但是,有几点值得注意:

  • this will only work if your run method reacts to interruption by stopping what it is doing
  • you could do the same thing more easily with a thread pool, for example by using one of the ExecutorService returned by the various factory methods provided by the Executors class. They would indeed handle the lifecycle of threads for you.
于 2013-01-09T21:32:45.110 回答
3

Firstly, starting 1000 threads is practically pointless as few of them will be scheduled to actually run concurrently.

Secondly, you can't "stop" threads. All you can do is ask them nicely via cooperative code to stop.

The easiest way to do what you want is to shutdown the JVM.

于 2013-01-09T21:33:43.810 回答