线程执行者 - 初学者

时间:2012-10-17 00:06:44

标签: java multithreading executorservice

我有两节课。在类A中,我将run()方法永久循环,而在类B中,我有线程池。

我的问题是,从类B,如何控制和停止在run()类中执行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());
    }
}

3 个答案:

答案 0 :(得分: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...
}

答案 1 :(得分:1)

ExecutorService#shutdownNow()上的文档说明了

  

除了尽力尝试停止处理主动执行任务之外,没有任何保证。例如,典型的实现将通过Thread.interrupt()取消,因此任何无法响应中断的任务都可能永远不会终止。

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

所以检查它是否被中断

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

而不只是做

while (true)

答案 2 :(得分:0)

可能在下面对你有用。

public static class A implements Runnable {
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("Hi");
        }
    }
}