2

我有两节课。在课堂A上,我有run()永远循环的方法,而在课堂B上,我有线程池。

我的问题是,从 ClassB中,如何控制和停止run()class 中的线程执行方法A,我尝试了 forceshutdown threadExecutor.shutdownNow(),但它不起作用。循环似乎永远持续下去。

这是示例代码:


public class A implements Runnable {
    public void run() {
        while (true) {
            System.out.println("Hi");
        }
    }
}

public class B {
    public static void main(String[] args) {
        int noOfThreads = 1;
        A ThreadTaskOne = new A();
        System.out.println("Threads are being started from Class B");
        ExecutorService threadExecutor = Executors.newFixedThreadPool(noOfThreads);
        threadExecutor.execute(ThreadTaskOne);
        threadExecutor.shutdownNow();
        System.out.println("B Ends, no of threads that are alive : " + Thread.activeCount());
    }
}
4

3 回答 3

1

正如@MadProgammer 所说,您的“无限”循环需要注意Thread.isInterrupted。例如(非常示意图)

public void run() {

   while (!Thread.isInterrupted()) {
      doSomethinginTheLoop1();
      blah...blah...blah
      // if the loop is very long you might want to check isInterrupted 
      // multiple times for quicker termination response
      doSomethingInTheLoop2();
   }

   // now, here's a decision of what you do
   // do you throw an InterruptedException or trust others to check interrupted flag.
   // read Java COncurrency in Practice or similar...
}
于 2012-10-17T00:20:22.820 回答
1

上的文件ExecutorService#shutdownNow()说 -

除了尽最大努力停止处理正在执行的任务之外,没有任何保证。例如,典型的实现将通过 Thread.interrupt() 取消,因此任何未能响应中断的任务可能永远不会终止。

而且你的线程似乎并不关心它是否被中断。

所以检查是否被中断

while (Thread.currentThread().isInterrupted())

而不仅仅是做

while (true)
于 2012-10-17T00:27:43.610 回答
0

可能下面对你有用。

public static class A implements Runnable {
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("Hi");
        }
    }
} 
于 2012-10-17T02:28:55.103 回答