|
| 1 | +package io.github.dunwu.javase.concurrent.lock; |
| 2 | + |
| 3 | +import java.util.concurrent.locks.Lock; |
| 4 | +import java.util.concurrent.locks.ReentrantLock; |
| 5 | + |
| 6 | +/** |
| 7 | + * ReentrantLock lockInterruptibly() 示例 |
| 8 | + * @author Zhang Peng |
| 9 | + * @date 2018/5/11 |
| 10 | + */ |
| 11 | +@SuppressWarnings("all") |
| 12 | +public class ReentrantLockDemo03 { |
| 13 | + |
| 14 | + private Lock lock = new ReentrantLock(); |
| 15 | + |
| 16 | + public static void main(String[] args) { |
| 17 | + ReentrantLockDemo03 demo = new ReentrantLockDemo03(); |
| 18 | + MyThread thread1 = new MyThread(demo); |
| 19 | + MyThread thread2 = new MyThread(demo); |
| 20 | + thread1.start(); |
| 21 | + thread2.start(); |
| 22 | + |
| 23 | + try { |
| 24 | + Thread.sleep(2000); |
| 25 | + } catch (InterruptedException e) { |
| 26 | + e.printStackTrace(); |
| 27 | + } |
| 28 | + thread2.interrupt(); |
| 29 | + } |
| 30 | + |
| 31 | + public void insert(Thread thread) throws InterruptedException { |
| 32 | + lock.lockInterruptibly(); //注意,如果需要正确中断等待锁的线程,必须将获取锁放在外面,然后将InterruptedException抛出 |
| 33 | + try { |
| 34 | + System.out.println(thread.getName() + "得到了锁"); |
| 35 | + long startTime = System.currentTimeMillis(); |
| 36 | + for (; ; ) { |
| 37 | + if (System.currentTimeMillis() - startTime >= Integer.MAX_VALUE) { break; } |
| 38 | + //插入数据 |
| 39 | + } |
| 40 | + } finally { |
| 41 | + System.out.println(Thread.currentThread().getName() + "执行finally"); |
| 42 | + lock.unlock(); |
| 43 | + System.out.println(thread.getName() + "释放了锁"); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + static class MyThread extends Thread { |
| 48 | + |
| 49 | + private ReentrantLockDemo03 demo = null; |
| 50 | + |
| 51 | + public MyThread(ReentrantLockDemo03 test) { |
| 52 | + this.demo = test; |
| 53 | + } |
| 54 | + |
| 55 | + @Override |
| 56 | + public void run() { |
| 57 | + try { |
| 58 | + demo.insert(Thread.currentThread()); |
| 59 | + } catch (InterruptedException e) { |
| 60 | + System.out.println(Thread.currentThread().getName() + "被中断"); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments