日期:2014-05-20  浏览次数:20787 次

为什么我正常运行代码跟我打断点以后运行的代码 结果不一样呢? (多线程ReentrantLock问题)
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

而且有时得到正确的结果 有时候不是正确的。。 谁知道为什么?

------解决方案--------------------
探讨
引用:

引用:
引用:

理解是正确的。

不过“出现一阵正确一阵错误的情况”,说明你的并发控制存在问题。

但是这个用Lock 锁 可以像synchronized那样用wait 和notify嘛?


可以,只是你直接运行的时候,没法控制哪个线程先执行,也就是哪个线程先获得锁你没法控制

就是说java本身的机制就是 ……