概要
操作的原子性
- 使用 synchronized 关键字,就是为了保证线程安全(操作的原子性)
- 即,线程内的变量 a/b 应该都自增成功
public class StopThread implements Runnable {
private int a = 0;
private int b = 0;
@Override
public void run() {
//保证线程安全(a和b的原子性)
synchronized (this) {
a++;
try {
//模拟耗时操作
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
b++;
}
}
public void print() {
System.out.println("value a = " + a + "|value b = " + b);
}
}
破坏线程安全的停止
Stop
- thread.stop
- 中断线程,并清除 监视器锁 信息
StopThread task = new StopThread();
Thread thread = new Thread(task);
thread.start();
//确保 task 获取到了 CPU
Thread.sleep(1000L);
//不正确的停止方法
thread.stop();
//value a = 1|value b = 0
task.print();
正确的线程停止
Interrupt
- InterruptException
- 当目标线程调用 ObjClz 的 wait()/wait(long)/wait(long, int)/join()/join(long, int)/sleep(long, int) 时候,线程中断状态将被清除,被抛出异常
- 当线程被 IO/NIO Channel 阻塞,同样会相应中断并抛出异常
- 如果以上条件不满足(线程正在运行),则只会设置中断标志位
手动检测中断状态
- 当线程在 Runnable 状态,中断不会被响应
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("thread status:" + Thread.currentThread().getState().toString());
}
}
});
thread.start();
//等待 thread 运行
Thread.sleep(200L);
thread.interrupt();
//在主线程sleep时,子线程会一直运行,不会被终止
Thread.sleep(3000L);
- 在循环时,检测中断标志位
- 线程会在主线程执行 interrupt 后,再次检测状态位时停止
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//检测中断标志
while (Thread.currentThread().isInterrupted()) {
System.out.println("thread 响应了中断");
}
System.out.println("thread status:" + Thread.currentThread().getState().toString());
}
});
thread.start();
//等待 thread 运行
Thread.sleep(200L);
thread.interrupt();
//在主线程sleep时,子线程会一直运行,不会被终止
Thread.sleep(3000L);