标签:1.7 family private color orm int 导致 text 共享资源
public class MainTest { public static void main(String[] args) throws InterruptedException { ReentrantLock lock = new ReentrantLock(); Thread threadA = new Thread(new ThreadA(lock)); threadA.setName("线程A"); Thread threadB = new Thread(new ThreadB(lock)); threadB.setName("线程B"); threadB.start(); Thread.sleep(1000); threadA.start(); } //测试线程B public class ThreadB implements Runnable{ private ReentrantLock lock; public ThreadB(ReentrantLock lock) { this.lock = lock; } public void run() { lock.lock(); try { System.out.println("B对象获得锁"); Thread.sleep(5000); }catch (Exception ex) { ex.printStackTrace(); }finally { lock.unlock(); } } } }
public class ThreadA implements Runnable{ private ReentrantLock lock; public ThreadA(ReentrantLock lock) { this.lock = lock; } public void run(){ lock.lock(); try { System.out.println("A对象获得锁"); }catch (Exception ex) { ex.printStackTrace(); }finally { lock.unlock(); } } } 指定结果: B对象获得锁 B对象等待5秒 A对象获得锁
public class ThreadA implements Runnable{ private ReentrantLock lock; public ThreadA(ReentrantLock lock) { this.lock = lock; } public void run(){ if (lock.tryLock()){ try { System.out.println("A对象获得锁"); }catch (Exception ex) { ex.printStackTrace(); }finally { lock.unlock(); } } } } 指定结果: B对象获得锁 B对象等待5秒
//测试线程A public class ThreadA implements Runnable{ private ReentrantLock lock; public ThreadA(ReentrantLock lock) { this.lock = lock; } public void run(){ try { lock.lockInterruptibly(); try { System.out.println("A对象开始中断"); Thread.currentThread().interrupt(); System.out.println("A对象结束中断"); }catch (Exception ex) { ex.printStackTrace(); }finally { System.out.println("A对象释放锁"); lock.unlock(); } } catch (InterruptedException e) { e.printStackTrace(); } } } 指定结果: B对象获得锁 A对象开始中断 A对象结束中断 A对象释放锁
public class ThreadA implements Runnable{ private ReentrantLock lock; public ThreadA(ReentrantLock lock) { this.lock = lock; } public void run(){ try { if (lock.tryLock(6, TimeUnit.SECONDS)){ try { System.out.println("A对象在6秒内获得锁"); }catch (Exception ex) { ex.printStackTrace(); }finally { lock.unlock(); } } } catch (InterruptedException e) { e.printStackTrace(); } } } 指定结果: B对象获得锁 B对象等待5秒 A对象在6秒内获得锁
标签:1.7 family private color orm int 导致 text 共享资源
原文地址:https://www.cnblogs.com/use-D/p/9740725.html