测试interrupt中断线程
1.
class StopRunnable implements Runnable{
@Override
public void run(){
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 测试停止线程");
}
}
public static void main(String[] args) {
StopRunnable runnable = new StopRunnable();
Thread t1 = new Thread(runnable);
t1.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t1.interrupt();
System.out.println("已经中断线程");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程结束");
}
}
测试结果:不能结束子线程
实际上interrupt()方法
设置了 isInterrupt 布尔值
结论: 如果线程中有wait()或者sleep休眠
这时调用interrupt方法 会抛出一个异常 InterruptedException
并且清除中断状态
如果线程中没有等待或者休眠
这时调用interrupt方法
会设置中断状态(true/false)的改变
测试interrupt清除状态
public static void main(String[] args) {
InterruptThread t1 = new InterruptThread();
InterruptThread t2 = new InterruptThread();
t1.start();
t2.start();
for (int i = 0; i < 50; i++) {
if (i == 25) {
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(i + "-------");
}
System.out.println("主线程结束");
}
}
class InterruptThread extends Thread{
public boolean isOver = false;
@Override
public synchronized void run() {
while (true) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "...run");
}
}
小结:线程等待相当于放弃了cpu的执行权
interrupt方法 尽量不要使用
如果要停止线程 直接使用标示法
只有遇到了 冷冻状态时 可以使用该方法
强行清除该状态
标记法中断线程
3.常用的标记法停止线程
public static void main(String[] args) {
StopRunnable runnable = new StopRunnable();
Thread t1 = new Thread(runnable);
t1.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runnable.isOver = true;
System.out.println("已经中断线程");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程结束");
}
}
class StopRunnable implements Runnable{
public boolean isOver = false;
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
long millis = System.currentTimeMillis();
while (System.currentTimeMillis() - millis < 1000) {
}
System.out.println(Thread.currentThread().getName() + " 测试停止线程");
}
}
}