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

求教关于线程的一个问题
该程序是看着马士兵老师的视频敲的, 为什么线程中的死循环一执行就不会结束, 刚学线程, 问题很菜
package TestTread1;

import java.util.Date;

public class TestSleep {
public static void main(String[] args) {
 MyThread thread = new MyThread ();
 thread.start();
try {
Thread.sleep(10000);
}catch(InterruptedException e) {}
MyThread.interrupted();//这里为什么不会中断线程, 视频里是可以的啊  


}
}


class MyThread extends Thread{
//可在此加一个boolean flag以此控制死循环
public void run() {
 
while(true) {
System.out.println("-----" + new Date() + "-----");
try {
sleep(1000);
}catch (InterruptedException e) {
return;
}
}
}
}
谢啦



------解决方案--------------------
因为你一直没有条件退出while(true)的循环
------解决方案--------------------
同意一楼,楼主总得设个bool变量,你的另一个线程可以控制这个变量的开关,但是循环中得判断这个变量,否则你那个循环肯定是走到黑的
------解决方案--------------------
你的原文有一句注释:
//可在此加一个boolean flag以此控制死循环

人家马老师都说了,只能说视频还没看懂,再好好看吧