zoukankan      html  css  js  c++  java
  • Interrupt笔记

    public static void main(String[] args) {
    Thread t=new Thread(new Runnable() {
    @Override
    public void run() {
    try {
    System.out.println("begin sleep");
    //Thread.interrupted()会清除中断标识为false,System.out.println(Thread.interrupted());
    //如果在还未阻塞的线程上调用interrupt()会给该线程的中断标识设为true,之后在调用抛出InterruptedException的阻塞方法时会立即抛出该异常。
                        Thread.sleep(2000);
    System.out.println("after throwing...");
    } catch (InterruptedException e) {
    System.out.println("after catching...");
    }
    System.out.println("exit run()...");
    }
    });
    t.start();
    try {
    TimeUnit.MILLISECONDS.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("t.interrupt() go");
    t.interrupt();
    System.out.println("t.interrupt() end");
    }

    结果:

    1:begin sleep
    2:t.interrupt() go
    3:t.interrupt() end
    4:after catching...
    5:exit run()...

    由于是两个线程,3、4、5顺序随机

      上面是中断sleep,接下来中断wait

      

      

    public static void main(String[] args) {
    Thread t=new Thread(new Runnable() {
    @Override
    public void run() {
    try {
    System.out.println("begin sleep");
                //wait()方法必须在同步块或同步方法中进行,并且锁的对象和调用对象需一致,否则会抛出java.lang.IllegalMonitorStateException的运行时异常
                        synchronized (Thread.currentThread()){
    Thread.currentThread().wait();
    }
    System.out.println("after throwing...");
    } catch (InterruptedException e) {
    System.out.println("after catching...");
    }
    System.out.println("exit run()...");
    }
    });
    t.start();
    try {
    TimeUnit.MILLISECONDS.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    System.out.println("t.interrupt() go");
    t.interrupt();
    System.out.println("t.interrupt() end");
    }

      结果:

    1:begin wait
    2:t.interrupt() go
    3:t.interrupt() end
    4:after catching...
    5:exit run()...

      由于是两个线程,3、4、5顺序随机

      另外interrup()方法无法中断IO阻塞和锁互斥阻塞,此时有两种解决方案

      1:关闭竞争的资源,比如:IO阻塞时,关闭阻塞的流,或者使用nio,nio提供了更人性化的中断响应,被阻塞的通道会自动响应中断。

      2:使用ReentrantLock的lockInterruptibly()方法来获取锁,此时锁互斥可以相应interrup()方法。

  • 相关阅读:
    POJ -- 3468
    HDOJ--1698
    简单的API应用
    Linux引导流程
    Python 实现网络爬虫小程序
    codeforce
    Count the string -- HDOJ 3336
    初次运行 Git 前的配置
    leetcode244- Shortest Word Distance II- medium
    leetcode243- Shortest Word Distance- easy
  • 原文地址:https://www.cnblogs.com/zou-rong/p/12544730.html
Copyright © 2011-2022 走看看