import java.util.*;
public class TestInterrupt { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread();
thread.start();
try{
Thread.sleep(10000);
}catch(InterruptedException e){
thread.interrupt();
}
}}
class MyThread extends Thread{
//boolean bl = true;
public void run(){
while(true){
System.out.println("========="+new Date()+"========");
try{
sleep(1000);
}catch(InterruptedException e){
return;
}
}
}
}
10秒之后不终止,一直跑,哪位高手帮解释一下呗,万分感谢,本人初学者。
public class TestInterrupt { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread();
thread.start();
try{
Thread.sleep(10000);
}catch(InterruptedException e){
thread.interrupt();
}
}}
class MyThread extends Thread{
//boolean bl = true;
public void run(){
while(true){
System.out.println("========="+new Date()+"========");
try{
sleep(1000);
}catch(InterruptedException e){
return;
}
}
}
}
10秒之后不终止,一直跑,哪位高手帮解释一下呗,万分感谢,本人初学者。
try{
Thread.sleep(10000);
}catch(InterruptedException e){
thread.interrupt();
} 我是用这个来控制 子线程的终止了吗 ? 这样不可以?
你可以这样写:
import java.util.*;
public class TestIter { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread thread = new MyThread();
thread.start();
try{
Thread.sleep(10000);
}catch(InterruptedException e){
e.printStackTrace();
} }}
class MyThread extends Thread{
//boolean bl = true;
public void run(){
while(true){
System.out.println("========="+new Date()+"========");
try{
sleep(1000);
interrupt();
}catch(InterruptedException e){
return;
}
}
}
}
MyThread thread = new MyThread();
thread.start();
try{
Thread.sleep(10000);
}catch(InterruptedException e){
thread.interrupt();
}
上面的代码应该写成下面这样
MyThread thread = new MyThread();
thread.start();
try{
Thread.sleep(10000);
}catch(InterruptedException e){
}//中断子线程
thread.interrupt();
sleep(1000);改成 sleep(10000)不就和你老师一模样