interrupt不管用

chen_xiangguo 2010-04-10 03:23:06
从java文档中得出:interrupt是中断线程,为此我做了个试验

public class Interrupt {
public static void main(String[] args) {
Runnable it=new InterruptTest();
Thread thread=new Thread(it);
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();
}
}
class InterruptTest implements Runnable {
@Override
public void run() {
int i=0;
while(true){
System.out.println(i++);
}
}

}

按理说2秒应该不打印才对,可是它一直打印个没完?
求高手
...全文
105 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 bao110908 的回复:]
while(true) 改成 while(Thread.currentThread().isInterrupted()) 再试试看。
[/Quote]

写错了,应该改成 while(!Thread.currentThread().isInterrupted()),少了个感叹号,嘿嘿
  • 打赏
  • 举报
回复
while(true) 改成 while(Thread.currentThread().isInterrupted()) 再试试看。
xiaoheixiadao 2010-04-10
  • 打赏
  • 举报
回复
你的try下面的语句就没执行...thread.start()方法执行后就会调用run方法,你的run方法里的while(true)循环是个死循环,会一直执行下去.并且你的thread.interrup()方法是单线程的话就没意义.你可以这样改:public class MyThread extends Thread{
private boolean stop = false;
int count=0;
@Override
public void run() {
while (!stop){
try {
Thread.sleep(2000);
count++;
stop = true;
System.out.println(count);
System.out.println("线程终止");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

public static void main(String[] asrgs) {

MyThread t = new MyThread();
t.start();
}
}
多个线程的时候才可以用其他线程来判断另一个线程是否中断

67,549

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧