为什么小弟我正常运行代码跟小弟我打断点以后运行的代码 结果不一样呢? (多线程ReentrantLock有关问题)
为什么我正常运行代码跟我打断点以后运行的代码 结果不一样呢? (多线程ReentrantLock问题)
源码如上
我打断点debug以后的运行结果是:
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
Acquired
tryLock(): false
tryLock(2,TimeUnit.SECONDS): false
但是正常直接run as java application后的结果:
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
Acquired
而且有时得到正确的结果 有时候不是正确的。。 谁知道为什么?
------解决方案--------------------
- Java code
package com.jit.test; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class AttemptLocking { private ReentrantLock lock = new ReentrantLock(); public void untimed() { boolean captured = lock.tryLock(); try { System.out.println("tryLock(): " + captured); } finally { if (captured) lock.unlock(); } } public void timed() { boolean captured = false; try { captured = lock.tryLock(2, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(); } try { System.out.println("tryLock(2,TimeUnit.SECONDS): " + captured); } finally { if (captured) lock.unlock(); } } public static void main(String[] args) { final AttemptLocking al = new AttemptLocking(); al.untimed(); al.timed(); new Thread() { { setDaemon(true); } public void run() { al.lock.lock(); System.out.println("Acquired"); } }.start(); Thread.yield(); al.untimed(); al.timed(); } }
源码如上
我打断点debug以后的运行结果是:
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
Acquired
tryLock(): false
tryLock(2,TimeUnit.SECONDS): false
但是正常直接run as java application后的结果:
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
tryLock(): true
tryLock(2,TimeUnit.SECONDS): true
Acquired
而且有时得到正确的结果 有时候不是正确的。。 谁知道为什么?
------解决方案--------------------