如下的一个小程序为什么进入循环之后无法退出呢? 请达人指教 小生感谢各位

yh_laoshu 2009-09-15 11:22:55
import java.util.Date;

public class TestInterruption {

public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
thread.sleep(10000);
} catch (InterruptedException e) {

thread.interrupt();
}

}

}

class MyThread extends Thread{
public void run(){
while(true){
System.out.println(new Date());
try {
sleep(1000);
} catch (InterruptedException e) {

return;
}
}
}
}


请教各位错误出现在哪里?
...全文
134 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
dz007 2009-09-16
  • 打赏
  • 举报
回复
先给thread加个终止标识,volatile boolean stop;

用try 包围while 这样中断后就跳到while外面了
try {
while(!stop){
………………
}
} catch (InterruptedException e) {

中断的时候先修改中断标识,再中断(原来那语句执行interrupt的时候不是sleep状态,那中断就无效)
thread.stop=true
thread.interrupt();
Allsochen 2009-09-16
  • 打赏
  • 举报
回复
哈哈,我也是从马士兵哪里开始学起的,想起一年前,我跟马士兵学习,感觉马士兵很牛,希望有机会能见到他本人。
yangfei_01 2009-09-16
  • 打赏
  • 举报
回复
4楼正解,lz看下大小写
gutan_fox 2009-09-16
  • 打赏
  • 举报
回复
import java.util.Date;

public class TestInterruption {

public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {

}

}

}

class MyThread extends Thread {
private int n;
public void run() {
while (true) {
System.out.println(new Date());
try {
sleep(1000);
n++;
if(n==5)
break;
} catch (InterruptedException e) {
return;
}

}
}
}

你的时死循环,你没有中断怎么会中断呢?可以在当满足某条件时,break它
yh_laoshu 2009-09-16
  • 打赏
  • 举报
回复
另外 对我楼上的那位兄弟说: 我按照你的改完以后怎么还是不行!?
yh_laoshu 2009-09-16
  • 打赏
  • 举报
回复
对呀 就是老马的 为什么我照抄就打不出来呢?
Allsochen 2009-09-16
  • 打赏
  • 举报
回复
import java.util.Date;

public class TestInterruption {

public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
//sleep是静态方法,要用类名去调用
Thread.sleep(10000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}

}

}

class MyThread extends Thread {
public void run() {
while (true) {
System.out.println(new Date());
try {
sleep(1000);
} catch (InterruptedException e) {

return;
}
}
}
}

打印十次就停止了,每一秒打印一次
Allsochen 2009-09-16
  • 打赏
  • 举报
回复
你是不是要打印十次时间就停止啊?
Allsochen 2009-09-16
  • 打赏
  • 举报
回复
貌似这个程序是在马士兵的视频里学的哦
yh_laoshu 2009-09-15
  • 打赏
  • 举报
回复
各位 帮帮忙啊 谢谢了

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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