我现在有个servlet 我想在init的时候加载一个线程,不断的执行某行代码,程序大致如下:
//---A.java servlet类-----
public class A extends HttpServlet {public void init(ServletConfig config) throws ServletException {
System.out.println("SoftWare initing......");
super.init(config);
B.doCk();
System.out.println("SoftWare inited!!");
}
public final void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
doPost(request, response);
} public final void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("HELLO WORLD!")
}
}
//---B.java 线程类-----
public class B extends Thread {
public void run() {
System.out.println("I'm Runing");
}
public static void doCk(){
B b = new B();
b.start();
int i=0;
while (true) {
System.out.println("I'm Runing "+i);
i++;
b.sleep(10000);
}
}
}
现在的情况是 B线程是运行了,也是在不断运行,但是这个工程的其他servlet就不能访问了,也走不到doGet或是doPost 甚至在我tomcat下的其他项目现在也无法访问了,现在就是卡在B.doCk()方法里不断运行,其他的运行不了了...web.xml 里我配置这个servlet是启动时就加载的.请问各位高手,怎么才能实现B.java不断运行,还不影响其他servlet和其他工程的运行
//---A.java servlet类-----
public class A extends HttpServlet {public void init(ServletConfig config) throws ServletException {
System.out.println("SoftWare initing......");
super.init(config);
B.doCk();
System.out.println("SoftWare inited!!");
}
public final void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
doPost(request, response);
} public final void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("HELLO WORLD!")
}
}
//---B.java 线程类-----
public class B extends Thread {
public void run() {
System.out.println("I'm Runing");
}
public static void doCk(){
B b = new B();
b.start();
int i=0;
while (true) {
System.out.println("I'm Runing "+i);
i++;
b.sleep(10000);
}
}
}
现在的情况是 B线程是运行了,也是在不断运行,但是这个工程的其他servlet就不能访问了,也走不到doGet或是doPost 甚至在我tomcat下的其他项目现在也无法访问了,现在就是卡在B.doCk()方法里不断运行,其他的运行不了了...web.xml 里我配置这个servlet是启动时就加载的.请问各位高手,怎么才能实现B.java不断运行,还不影响其他servlet和其他工程的运行
public
staticvoid doCk(){B b = new B();
b.start();
int i=0;
while (true) {
System.out.println("I'm Runing "+i);
i++;
b.sleep(10000);
}
public void init(ServletConfig config) throws ServletException {
System.out.println("SoftWare initing......");
super.init(config);
new B().start(); // 这才是启动线程
System.out.println("SoftWare inited!!");
}public void run() { // 这才是线程启动后的执行函数
System.out.println("I'm Runing");
int i=0;
while (true) {
System.out.println("I'm Runing "+i);
i++;
sleep(10000);
}
}
要写到run()方法里面
int i=0;
while (true) {
System.out.println("I'm Runing "+i);
i++;
sleep(10000);
这段代码都要放在run方法里才对,按照你现在的写法,你的线程早就运行结束了,只是在doCk()里做死循环
这位高手说的还靠谱,但是好像sleep不行,我改成wait了 已经实现我想要的效果了.十分感谢