生活随笔
收集整理的這篇文章主要介紹了
代码演示:获取锁时被中断
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
lockInterruptibly()
- lockInterruptibly():相當(dāng)于tryLock(long time, TimeUnit unit)把超時時間設(shè)置為無限,在等待鎖的過程中,線程可以被中斷
unlock()
package lock.lock;import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class LockInterruptibly implements Runnable {private Lock lock = new ReentrantLock();
public static void main(String[] args) {LockInterruptibly lockInterruptibly = new LockInterruptibly();Thread thread0 = new Thread(lockInterruptibly);Thread thread1 = new Thread(lockInterruptibly);thread0.start();thread1.start();try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}thread1.interrupt();
}@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "嘗試獲取鎖");try {lock.lockInterruptibly();try {System.out.println(Thread.currentThread().getName() + "獲取到了鎖");Thread.sleep(5000);} catch (InterruptedException e) {System.out.println(Thread.currentThread().getName() + "睡眠期間被中斷了");} finally {lock.unlock();System.out.println(Thread.currentThread().getName() + "釋放了鎖");}} catch (InterruptedException e) {System.out.println(Thread.currentThread().getName() + "獲得鎖期間被中斷了");}}
}
?
總結(jié)
以上是生活随笔為你收集整理的代码演示:获取锁时被中断的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。