我有两节课。在课堂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());
}
}