我想的是可以在web.xml中配置一个servlet的,但是我改怎么配置,叫WEB服务开启时,就运行这个servlet,然后就执行我的哪个线程程序?
以上只是一些想法,不知有没有别的好的方法?

解决方案 »

  1.   

    使用Servlet init;struts可以使用plug-in
    public class BackGroundServlet
        extends HttpServlet {  //Initialize global variables
      public void init() throws ServletException {
        try {
           // you code
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }web.xml
      <servlet>
        <servlet-name>backgroundservlet</servlet-name>
        <servlet-class>com.**.BackGroundServlet</servlet-class>
        <load-on-startup>30</load-on-startup>
      </servlet>
      

  2.   

    <load-on-startup>30</load-on-startup> 值>0就可以了
      

  3.   

    可是我现在每个线程都是独立的一个类
    并且都有main()方法来启动线程
    一共5个线程
    我怎么在servlet中调用类的主方法?
      

  4.   

    你不会把main()的代码复制到init() 里?
      

  5.   

    我使用Servlet init测试用了,有一定问题
    线程是个死循环得不停的运行才可以的,我在servlet中调用了之后,程序就在哪里不往下运行了
      

  6.   

    那你所谓线程并不是线程,demo:
    public class TestThred    extends Thread {
      public TestThred() {
      }  public void run() {
        //you code  }
    }
    使用:
      Thread thraed = new TestThred();
      thraed.start();//不是 .run();
      

  7.   

    或者
      public class TestThread
        implements Runnable {
        public void run() {
     
        }
      }
    使用:
     (new Thread(new TestThread())).start();
      

  8.   

    最好不要直接用死循环,这很耗资源,可以挂起一会儿
    while (true) {
        ...
        try { //暂停一秒
              Thread.sleep(1000);
        } catch (InterruptedException e) {
              System.out.println(e.toString());
        }
    }
      

  9.   

    以上问题我当然知道,//暂停多少时间有什么关系
    我的问题是现在怎么加到程序中叫它就开启线程后还可以继续下面的运行别的模块代码
    不是在一个模块中的别的方法,现在
    thraed.start();
    它就会一直在哪里运行,不会返回到别的类去执行
      

  10.   

    执行 thraed.start()后,他会跟着执行后面的代码,并不会停上,thraed在另一个进程里运行,到于你要Thread.sleep(1000),那是你thraed里内的事情了,或者你可以考滤用定时执行器:Timer