初心
用interrupt中断程序
初步实现
public class InterruptionInJava implements Runnable{
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Yes!! I'm Interupted, but I'm still running");
} else { }
}
// System.out.println("Oh, myGod!");
} public static void main(String[] args) {
Thread thread = new Thread(new InterruptionInJava(), "testThread");
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
System.out.println("Begin Interupt...");
thread.interrupt();
System.out.println("End Interupt...");
}
}
输出
Yes!! I'm Interupted, but I'm still running
Yes!! I'm Interupted, but I'm still running
Yes!! I'm Interupted, but I'm still running
Yes!! I'm Interupted, but I'm still running
Yes!! I'm Interupted, but I'm still running
Yes!! I'm Interupted, but I'm still running
Yes!! I'm Interupted, but I'm still running
.....
问题:虽然是被中断状态,但实际并未中断
interrupt说明
在java中主要有3个相关方法,interrupt(),isInterrupted()和interrupted()。
- interrupt(),在一个线程中调用另一个线程的interrupt()方法,即会向那个线程发出信号——线程中断状态已被设置。至于那个线程何去何从,由具体的代码实现决定。
- isInterrupted(),用来判断当前线程的中断状态(true or false)。
- interrupted()是个Thread的static方法,用来恢复中断状态(!!!)
解决不中断问题
处于被中断状态时,return 或 bread 中断线程
public class InterruptionInJava implements Runnable{
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Yes!! I'm Interupted, but I'm still running");
return;
} else { }
}
} public static void main(String[] args) {
Thread thread = new Thread(new InterruptionInJava(), "testThread");
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
System.out.println("Begin Interupt...");
thread.interrupt();
System.out.println("End Interupt...");
}
}
等价开关
public class InterruptionInJava2 implements Runnable{
private volatile static boolean on = false; @Override
public void run() {
while (!on) {
try {
System.out.println("begin Sleep");
Thread.sleep(10000000);
System.out.println("end Sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Oh, myGod!");
}
} public static void main(String[] args) {
Thread thread = new Thread(new InterruptionInJava2(), "testThread");
thread.start();
try {
System.out.println("main Begin sleep");
Thread.sleep(5000);
System.out.println("main End sleep");
} catch (InterruptedException e) { }
InterruptionInJava2.on = true;
}
}
使用静态变量on
但是在run方法中Thread.sleep(10000000),