Slervlet中的代码:
ThreadClass thread = null;
String method=request.getParameter("method");
  System.out.println(method);
   //开始线程
   if(method.equals("start"))
     {
thread=new ThreadClass();
thread.start();
      }
   //停止线程
    else if(method.equals("stop"))
     {
System.out.println(thread);
System.out.println(thread.isAlive());
thread.stopthread();
      }
   //暂停线程
    else if(method.equals("suspend"))
     {
System.out.println(thread);
System.out.println(thread.isAlive());
          try {
thread.sleep(20000);
     } catch (InterruptedException e) {
     e.printStackTrace();
  }
 }ThreadClass代码:
    public class ThreadClass extends Thread {
         public boolean flag = false;
boolean runflag = false;
public synchronized void stopthread() {
runflag = true;
}
public synchronized boolean getrunflag() {
return runflag;
}
public void run() {
try {
while (!getrunflag()) {
   getall();
}
} catch (Exception e) {
e.printStackTrace();
}
} public void getall() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(1000);
System.out.println("thread" + i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
  小弟想实现的功能是,一个线程开始运行后,想停止、暂停、继续运行这个线程,从页面上传不同的标识到servlet中进行不同的操作!我现在做出的停止功能是:当运行了thread.stopthread()后,线程还在运行,只有当线程这个一循环结束了,线程才停止,而我现在想立刻停止,怎么办??而且如果我不用thread.stopthread()来改变runflag的值的话,线程循环一次结束后会一直循环下去,而不是循环一次后线程自动停止!再有就是怎么样让线程暂停、继续运行线程啊?我使用sleep(2000)不行吗!小弟刚开始学习线程,希望各位教教小弟!十分感谢!!!

解决方案 »

  1.   

      那你有没有什么方法停止线程啊?最好不要用while(标识)!!!
      

  2.   

    不知道你这个需求为什么必须用一个线程实现?而且是在servlet里?servlet本来就是多线程的,你根本没法控制。而且线程调度是cpu jvm做的事,你没法干预的
      

  3.   

    这个只是我做的一个小例子,我现在在做nutch相关的项目,我们用的就是servlet+javabean来开发的,现在客户想要能对nutch进行暂停、停止等操作,只能对线程进行操作!
      

  4.   

    你在这个循环里再加一个判断
    for (int i = 0; i < 20; i++) {
    if(getrunflag()) 
    {
         Thread.sleep(1000);
         System.out.println("thread" + i);
    }
    else
    break;}
      

  5.   


    谢谢,第一个问题解决了,现在能直接停止线程了!!现在怎么暂停线程呢?在servlet中用thread.sleep()或thread.wait()好像都不能使线程暂停,有人知道怎么做吗???
      

  6.   

    建议你用任务的方式发信息到任务队列中,  等线程去拿到任务以后判段是否是要停止啊,  还可以给任务加标识只能特定的线程执行才睡觉,  你可以把线程睡在一个特定的对象上, 如你要叫醒他就只要到这对象的方法中notify
      

  7.   

    servlet中已经是一个单实例多线程的形式的。你讲的这个操作好像真的没有必要呀。
      

  8.   

    wait();线程停
    notify();唤醒线程