• sleep wait join 的线程如果被打断,会直接清除打断标记,将打断标记设置为false

  1. public class WaitNotifyInterupt {
  2. static Object obj = new Object();
  3. public static void main(String[] args) {
  4. Thread threadA = new Thread(() -> {
  5. synchronized (obj) {
  6. try {
  7. System.out.println("begin");
  8. obj.wait();
  9. System.out.println("end");
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. });
  15. threadA.start();
  16. try {
  17. Thread.sleep(1000);
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. threadA.interrupt();
  22. System.out.println("Thread end");
  23. }
  24. }

为什么sleep的线程被打断之后会清除打断标记?

正常线程调用interrupt()不能被打断 给你一个打断标记你自己根据标记去判断
如果是sleep则会响应打断所以会清除打断标记;

  1. import java.util.concurrent.TimeUnit;
  2. class Lock3 {
  3. public static void main(String[] args) throws InterruptedException {
  4. Thread t1 = new Thread(() -> {
  5. System.out.println("t1------");
  6. try {
  7. TimeUnit.SECONDS.sleep(100);
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. }, "t1");
  12. t1.start();
  13. //主要为了让子线程 t1先运行
  14. TimeUnit.SECONDS.sleep(1);
  15. //本来你这里做了对t1的打断操作 为什么sleep要清除
  16. t1.interrupt();
  17. //false
  18. System.out.println("t1的打断标记" + t1.isInterrupted());
  19. }