java 线程问题 启动+停止。Runnable实现 或 Thread 继承 均可。
--------------------编程问答-------------------- 自己顶一下吧。高手帮忙写一个吧。谢谢。。 --------------------编程问答-------------------- 首先,请注意,你的需求是不合理的:一般性规范不建议你在中间件中独立控制线程,这很容易引发各种奇怪的并发问题。
从纯技术可行性角度而言,仍然给出一个参考实现(因为我懒,就没有拆分成Java类了):
--------------------编程问答-------------------- 代码亲测,还是不行。继续等待高手帮忙解决。谢谢2楼这位大哥。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%!
private volatile static MyThread runner = null;
private static class MyThread extends Thread {
private volatile boolean run = true;
public void abort() {
run = false;
}
public void run() {
try {
while (run) {
System.out.println("Running: " + new Date());
Thread.sleep(1000);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
%>
<%
response.setHeader("Cache-Control", "no-cache, no-store"); //HTTP 1.1
response.setHeader("Pragma", "no-cache"); //HTTP 1.0
response.setDateHeader("Expires", 0); //prevents caching at the proxy server
String msg = "请选择:";
String cmd = request.getParameter("cmd");
if (cmd != null) {
synchronized(MyThread.class) {
if ("start".equals(cmd)) {
if (runner != null) {
msg = "线程已经处于运行中,不能重复启动!" + msg;
} else {
runner = new MyThread();
runner.start();
msg = "线程已启动;" +msg;
}
} else if ("abort".equals(cmd)) {
if (runner == null) {
msg = "线程还没有启动过,没东西给你停止!" + msg;
} else {
runner.abort();
runner = null;
msg = "线程已停止;" +msg;
}
}
}
}
%>
<html>
<body>
<p><%=msg%></p>
<p></p>
<p><a href="?cmd=start">启动</a> <a href="?cmd=abort">停止</a></p>
</body>
</html>
--------------------编程问答--------------------
我测是好使的啊、
汗、
请点击完按钮看自己的控制台、
--------------------编程问答--------------------
你是怎么测试的?我这段代码在我本机是试验没问题的。 --------------------编程问答-------------------- 我不知道 为啥要在jsp写线程? --------------------编程问答-------------------- 我测试了也没问题,看看控制台流程是达到了,还是你的需求没有表达清楚? --------------------编程问答-------------------- 使用JSP代码写是没有问题的,但是如果拆分到 java 中 就不会成功。
if (runner != null) {
msg = "线程已经处于运行中,不能重复启动!" + msg;
}
2#的楼主可以试一下。希望抽时间帮忙再写一下。谢谢。
--------------------编程问答-------------------- 都到這程度了。。。。。。。 --------------------编程问答-------------------- 使用JSP代码写是没有问题的,但是如果拆分到 java 中 就不会成功。
普科学生 --------------------编程问答-------------------- 帮你写了个,可以运行的,在JSP上你就自己写两个按钮去调用qidong()和stopService()就好了
public class Test {--------------------编程问答-------------------- 除
private static boolean loop = true;
public void qidong() throws InterruptedException {
loop =true;
final Test test = new Test();
if(!loop){
new Thread(new Runnable(){
public void run() {
try {
test.stopService();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();}
if(loop){
test.handle();
}
}
public void stopService() throws InterruptedException{
this.loop=false;
System.out.println("停止了");
}
public void handle() throws InterruptedException {
while(loop) {
System.out.println(new Date().toString);
Thread.sleep(1000);
}
}
}
补充:Java , Java EE