我在glassfish下部署了一个JSF Web应用程序,其中我有两个按钮。第一个启动无限线程,第二个停止它。我的问题是我无法停止正在运行的线程。我已经搜索了一个解决方案网但是徒劳。如果我有一个J2SE应用程序而不是J2EE应用程序,这是我的代码
package com.example.beans;
import org.apache.commons.lang.RandomStringUtils;
public class MyBusinessClass {
public static void myBusinessMethod() {
/* this method takes a lot of time */
int i = 1;
while (i == 1) {
String random = RandomStringUtils.random(3);
System.out.println(random);
}
}
}
package com.example.beans;
import java.util.Random;
import java.util.TimerTask;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.log4j.Logger;
import com.example.core.RandomUtils;
public class MySimpleRunnableTask implements Runnable {
private Logger logger = Logger.getLogger(MySimpleRunnableTask.class);
@Override
public void run() {
MyBusinessClass.myBusinessMethod();
}
}
@ManagedBean(name = "MainView")
@SessionScoped
public class MainView {
private static Thread myThread;
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
public String startSimpleThread() throws SecurityException,
NoSuchMethodException,
InterruptedException {
MySimpleRunnableTask mySimpleRunnableTask = new MySimpleRunnableTask();
myThread = new Thread(mySimpleRunnableTask);
myThread.start();
return null;
}
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
public String stopSimpleThread() throws SecurityException,
NoSuchMethodException,
InterruptedException {
myThread.interrupt();
return null;
}
}
我已经更改了我的代码,因此您可以真正了解我的问题
答案 0 :(得分:0)
interrupt仅将线程中的中断状态设置为true。线程需要定期汇集中断状态标志以停止运行:
public void run() {
/* you will have to touch the code here */
int i = 1;
while (i == 1) {
String random = RandomStringUtils.random(3);
logger.info(random);
if (Thread.currentThread().isInterrupted()) {
// the thread has been interrupted. Stop running.
return;
}
}
}
这是正确停止线程的唯一方法:让他停下来。如果没有来自正在运行的线程的合作,就没有干净的方法。