日期:2014-05-20 浏览次数:20799 次
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>