Java 哪位大哥帮我看下这程序怎么结束不了了!!

来源:百度知道 编辑:UC知道 时间:2024/05/27 06:12:44
import java.util.*;

public class Test1{
public static void main(String[] agrs){
//try{
Thread a = new Thread(new Runnable(){
public void run(){
try{
while(true){
Thread.sleep(1000);
System.out.println("###" + new Date() + "###");
}
}
catch(InterruptedException e){
return;
}
}
});
a.start();
try{
Thread.sleep(10000);
}
catch(InterruptedException e){
}
a.interrupted();
//}
}
}
就是想它运行10秒停止!

要用a.interrupt(),不是a.interrputed()。
你调用的方法是判断这个线程是否被中断了,而不是去中断这个线程。
你看一下方法返回值就知道了。

======================
将a.interrupted(); 改为
a.interrupted();
a.stop();即可
我已运行测试通过 呵呵

原因:
线程Thread a = new Thread()实例化为a之后,线程的启动和停止应该由实例去调用start()和stop()方法 调用方式为a.stop();

======================
import java.util.*;

public class Test1{
public static void main(String[] agrs){
//try{
Thread a = new Thread(new Runnable(){
public void run(){
try{
while(true){
Thread.sleep(1000);
System.out.println("###" + new Date() + "###");
}
}
catch(InterruptedException e){
return;
}
}
});
a.start();
try{
Thread.sleep(10000);
}
catch(InterruptedException e){
}
a.interrupted();
a.stop();
//}
}
}

他们说的挺对的