Java停止线程从类运行的所有线程

use*_*236 7 java

我需要做的是能够阻止从一个实现runnable的线程类运行的所有线程.这就是我的意思:这是我的"线程"类的开头:

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()
  {
Run Code Online (Sandbox Code Playgroud)

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

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

m是要创建的线程数.这可以是50-1000.现在我需要做的就是突然停止所有这些.我怎样才能做到这一点?

Shi*_*vam 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();
 }
Run Code Online (Sandbox Code Playgroud)

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

for(Thread thread : threads)
{
    thread.interrupt();
}
Run Code Online (Sandbox Code Playgroud)

确保签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);
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 让我们只希望线程上没有阻塞IO. (4认同)
  • 或者是一个没有检查线程中断状态的while循环...... (4认同)