我在写jsp时候,想要实现一个类似开关的功能——页面有一个按钮或者链接,开始显示“开启连接”,点击一下,标签变成“关闭连接”,同时开启进程Server,Server是一个继承了Runnable的类,我把它的定义放在另一个jsp页面里,主要实现的是对一个端口进行监听。上面说的那个标签变成“关闭连接”后,再点击一下,标签又变成“开启连接”,同时,关闭之前定义的对端口监听的进程,如此循环。下面的判断是跟在Server类后面的语句,就是关闭进程开启进程的,我运行下面程序,点击以后,标签文字会自动改变,但是进程好像没法关,我试过用System.out.println打印出两次的进程ID,结果显示的PID都是一致的,但是就是关闭不了进程。if(session.getAttribute("label").equals("开启连接"))
    {
     Thread t=new Thread(new Server());
     session.setAttribute("label","关闭连接");
         System.out.println(c.getId());
     session.setAttribute("Thread_conn",t);
     t.start();
     }
else{
     session.setAttribute("label","开启连接");
     Thread tc=(Thread)session.getAttribute("Thread_conn");
         System.out.println(tc.getId());
     tc.stop();
}
response.setHeader("refresh","0;URL=canguan.jsp");

解决方案 »

  1.   

    上面代码第五行,应该是System.out.println(t.getId());
      

  2.   

    //显示进程
    Process process = Runtime.getRuntime().exec("tasklist");Scanner in=new Scanner(process.getInputStream());
    while(in.hasNextLine()){
    String p=in.nextLine();
    //打印所有进程
    System.out.println(p);
    if(p.contains("javaw.exe")){
    StringBuffer buf=new StringBuffer();
    for(int i=0;i<p.length();i++){
    char ch=p.charAt(i);
    if(ch != ' '){
    buf.append(ch);
    }
    }
    //打印 javaw.exe的pid
    System.out.println(buf.toString().split("Console")[0].substring("javaw.exe".length()));
    }
    }//杀死进程,1,纯dos下,开cmd窗口 ntsd -c q -p PID
    //Runtime.getRuntime().exec("ntsd -c q -p 1528");
    //2 ,tskill PID(process ID)
    //Runtime.getRuntime().exec("tskill 3188");