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

线程打断问题
我这个线程为何没有被打断了 求解?

import java.util.Date;
public class Thread_interrupt
{
/**
 *线程打断
 *????为何无效 进程没打断????
 */
public static void main(String[] args)
{
MyThread thread = new MyThread();
thread.start();
try
{
Thread.sleep(5000);
} 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)
{
System.out.println("进程被打断");
return;
}
}
}
}
多线程 打断

------解决方案--------------------
我想你的输出语句应该放在catch里边才行吧
------解决方案--------------------
InterruptedException 是强行被打断才会触发的,你既然让主线程睡眠5秒在区打断子线程,那么就写在try语句块中啊,catch我说了死循环,除非你还有线程区打断主线程,触发其catch语句块的执行。还有,就目前你的代码来看,主,子线程各自sleep然后轮流交替主动权,没有发生争抢,更别提打断了~