记录Java线程相关知识

158 阅读1分钟

知识总结

  • 线程wait的时候,会释放monitor,等到被notify的时候再次去抢夺monitor
  • interrupt()会打断wait,sleep,并且抛出InterruptedException异常,并且isInterrupted()会被重置
  • isInterrupted()以及InterruptedException都会导致isInterrupted()被重置为false
  • Thread.sleep()方法在Android中可以用SystemClock.sleep()替代,不用写try...catch...

知识普及

  • 重入锁
    //确保同一线程可以重复进入,并且同时只能由一个线程访问。
    Lock mLock = new ReentrantLock();
    mLock.lock();
    try{
        ...
    }finally{
        mLock.unlock();//务必在finally中unlock,否则如果发生异常,其他线程就被永远阻塞了
    }
    

QA

  1. 为什么wait(),notify()要写在synchronized

    为什么呢?

  2. 圣诞节福利时间