zoukankan      html  css  js  c++  java
  • 线程中断

    当一个线程处于阻塞状态时,需要提供一种唤醒机制。例:

     1    public static void main(String[] args) {
     2         Thread t = new Thread(() -> {
     3             try {
     4                 Thread.sleep(5000);
     5             } catch (InterruptedException e) {
     6                 System.out.println(Thread.currentThread().isInterrupted());
     7             }
     8         });
     9 
    10         t.start();
    11         t.interrupt();
    12     }

    子线程 t 在执行的过程中睡着了,主线程等不及了,提醒子线程(设置子线程的中断标志),sleep这个动作可以响应中断,清除中断状态,然后抛出异常(下方模拟实现)。打印出来的中断标志是false。

    public void throwInterruptedException() throws InterruptedException{
        if (Thread.interrupted()) //获取中断状态后,会重新复原
                throw new InterruptedException();
    }

    怎么处理捕获到的中断异常呢?

    1. 抛到上层

    2. 重设线程的中断标志,交由上层判断

        public static void main(String[] args) throws InterruptedException {
            Thread t = new Thread(() -> {
                while (!Thread.currentThread().isInterrupted()) {
                    skating();
                }
                System.out.println("开始干活");
            });
    
            t.start();
    
            Thread.sleep(500);
            t.interrupt();
    
        }
    
        private static void skating() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                System.out.println("被发现了:_(");
                Thread.currentThread().interrupt();
            }
        }
    人生就像蒲公英,看似自由,其实身不由己。
  • 相关阅读:
    hdu 5726 GCD
    codeforces 982C Cut 'em all!
    codeforces 982B Bus of Characters
    codeforces 982A Row
    codeforces 983B XOR-pyramid
    codeforces 979D Kuro and GCD and XOR and SUM
    codeforces 983A Finite or not?
    codeforces 984B Minesweeper
    codeforces 979C Kuro and Walking Route
    codeforces 979B Treasure Hunt
  • 原文地址:https://www.cnblogs.com/walker993/p/14325458.html
Copyright © 2011-2022 走看看