日期:2014-05-20  浏览次数:20744 次

懂java线程中断的朋友帮忙看看
想在jsp页面控制线程的开启与中断。现在搞不定。是不是不可行?
Java code

package com.thread.demo;

public class ATask implements Runnable{
    public void run() {
         try {
            while (true) {
                System.out.println("I am running!");
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            System.out.println("ATask.run() interrupted!");
        }
    }
}

package com.thread.demo;

public class InterruptTaskTest {
 
     public static void main(String[] args) throws Exception{
        Thread t = new Thread(new ATask());
        System.out.println("test1:"+t);
        t.start();
        System.out.println("test2:"+t);
        t.interrupt();
        System.out.println("test3:"+t);
    }
    //直接用类运行的话,肯定能抛出InterruptedException中断线程。页面的话就是相当不是同一个线程了。难解!

<%@ page language="java" import="java.util.*,com.thread.demo.*,java.io.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <body>
    <a href="javascript:location.href='index.jsp?action=on'">打开</a>
    <a href="javascript:location.href='index.jsp?action=stop'">关闭</a>
    <%
    String action=request.getParameter("action");
    Thread t = new Thread(new ATask());
    System.out.println("test1:"+t);
    if("on".trim().equals(action))
    {
    t.start();
    }
    System.out.println("test2:"+t);
   if("stop".trim().equals(action))
   {
    t.interrupt();
   }
    System.out.println("test3:"+t);
    %>
    
  </body>
</html>




------解决方案--------------------
我是菜鸟,线程不懂的说,

public void interrupt()中断线程。 
如果当前线程没有中断它自己(这在任何情况下都是允许的),则该线程的 checkAccess 方法就会被调用,这可能抛出 SecurityException。 

如果线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个 InterruptedException。

你捕获下这个异常么。 


------解决方案--------------------
探讨
Thread t = new Thread(new ATask());