import java.util.Date;public class TestInterruption { public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
thread.sleep(10000);
} 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) {
return;
}
}
}
}
请教各位错误出现在哪里?
MyThread thread = new MyThread();
thread.start();
try {
thread.sleep(10000);
} 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) {
return;
}
}
}
}
请教各位错误出现在哪里?
MyThread thread = new MyThread();
thread.start();
try {
//sleep是静态方法,要用类名去调用
Thread.sleep(10000);
thread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
} }}class MyThread extends Thread {
public void run() {
while (true) {
System.out.println(new Date());
try {
sleep(1000);
} catch (InterruptedException e) { return;
}
}
}
}
打印十次就停止了,每一秒打印一次
MyThread thread = new MyThread();
thread.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
} }}class MyThread extends Thread {
private int n;
public void run() {
while (true) {
System.out.println(new Date());
try {
sleep(1000);
n++;
if(n==5)
break;
} catch (InterruptedException e) {
return;
}
}
}
}
你的时死循环,你没有中断怎么会中断呢?可以在当满足某条件时,break它
try {
while(!stop){
………………
}
} catch (InterruptedException e) { 中断的时候先修改中断标识,再中断(原来那语句执行interrupt的时候不是sleep状态,那中断就无效)
thread.stop=true
thread.interrupt();