大家帮我看看这个程序为什么不行
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class vote extends HttpServlet implements Runnable {
long candidate1=0;
long candidate2=0;
long candidate3=0;
boolean stopflag=false;
Thread t;
public void init(){
t=new Thread(new vote());
t.start();
}
public void run() {
while(true){
candidate1=100;
candidate2=(long) (candidate2+ Math.random()*10);
candidate3=(long) (candidate3+ Math.random()*10);
System.out.println("c1:"+candidate1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws
ServletException,
IOException{
response.setContentType("text/html");
response.setHeader("refresh","5");
PrintWriter out =response.getWriter();
System.out.println(candidate1);
out.println(
"<html>"+
"<head><title> show vote rate! </title></head>"+
"<body><center>"+
"<h1> Vote</h1>"+
new Date()+"<br>"+
"candidate1:"+candidate1+"<br>"+
"candidate2:"+candidate2+"<br>"+
"candidate3:"+candidate3+"<br>"+
"</center></body></html>"
);
}
}
就是线程里面产生的数在doGet里面读不到
------解决方案--------------------t=new Thread(new vote());
t.start();
这里new了一个新的vote对象, 你当前的doGet()中用的还是本voite的值。。。。。肯定一直都是0了
还有你这种写法,long candidate1=0;
long candidate2=0;
long candidate3=0; 这3个变量在多线程下是非线程安全的
------解决方案--------------------问题已说清,楼主快结贴,给分。。