class MyThread9 implements Runnable{
public void run(){
System.out.println("1、进入run方法");
try{
Thread.sleep(10000); //休眠10s
System.out.println("2、已经完成休眠");
}catch(Exception e){
System.out.println("3、休眠被终止");
return; //让程序返回被调用处
}
System.out.println("4、方法正常结束");
}
}
public class ThreadInterruptDemo { public static void main(String[] args) {
MyThread9 mt = new MyThread9();
Thread t =new Thread(mt,"线程");
t.start();
try{
Thread.sleep(2000); //稍微停2s再继续中断
}catch(Exception e){
}
t.interrupt(); //中断线程执行
}}
这个的结果是
1、进入run方法
3、休眠被终止
当我改成这样的时候class MyThread9 implements Runnable{
public void run(){
System.out.println("1、进入run方法");
try{
Thread.sleep(10000); //休眠10s
System.out.println("2、已经完成休眠");
}catch(Exception e){
System.out.println("3、休眠被终止");
return; //让程序返回被调用处
}
System.out.println("4、方法正常结束");
}
}
public class ThreadInterruptDemo { public static void main(String[] args) {
MyThread9 mt = new MyThread9();
new Thread(mt,"线程").start();;
try{
Thread.sleep(2000); //稍微停2s再继续中断
}catch(Exception e){
}
new Thread(mt,"线程").interrupt(); //中断线程执行
}}
输出结果是
1、进入run方法
2、已经完成休眠
4、方法正常结束
这是什么原因?第一个是实例化Thread类对象来调用的start()和interrupt()方法
第二个是直接用匿名对象来调用(这是匿名对象调用吧,我没弄错撒)
这两个结果怎么会不同?
public void run(){
System.out.println("1、进入run方法");
try{
Thread.sleep(10000); //休眠10s
System.out.println("2、已经完成休眠");
}catch(Exception e){
System.out.println("3、休眠被终止");
return; //让程序返回被调用处
}
System.out.println("4、方法正常结束");
}
}
public class ThreadInterruptDemo { public static void main(String[] args) {
MyThread9 mt = new MyThread9();
Thread t =new Thread(mt,"线程");
t.start();
try{
Thread.sleep(2000); //稍微停2s再继续中断
}catch(Exception e){
}
t.interrupt(); //中断线程执行
}}
这个的结果是
1、进入run方法
3、休眠被终止
当我改成这样的时候class MyThread9 implements Runnable{
public void run(){
System.out.println("1、进入run方法");
try{
Thread.sleep(10000); //休眠10s
System.out.println("2、已经完成休眠");
}catch(Exception e){
System.out.println("3、休眠被终止");
return; //让程序返回被调用处
}
System.out.println("4、方法正常结束");
}
}
public class ThreadInterruptDemo { public static void main(String[] args) {
MyThread9 mt = new MyThread9();
new Thread(mt,"线程").start();;
try{
Thread.sleep(2000); //稍微停2s再继续中断
}catch(Exception e){
}
new Thread(mt,"线程").interrupt(); //中断线程执行
}}
输出结果是
1、进入run方法
2、已经完成休眠
4、方法正常结束
这是什么原因?第一个是实例化Thread类对象来调用的start()和interrupt()方法
第二个是直接用匿名对象来调用(这是匿名对象调用吧,我没弄错撒)
这两个结果怎么会不同?
是又new了一个线程,而且这个线程又没有启动,直接中断了,所以不会影响前面的线程。LZ可以考虑改造下MyThread9,增加一个String name的属性,打印的时候顺带把name打印出来,这样就清晰的知道那些字符串是哪个线程打印的了。