java中对线程的操作?(开始、停止、暂停)
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)不行吗!小弟刚开始学习线程,希望各位教教小弟!十分感谢!!!